Problem is that map does not work on Set: https://stackoverflow.com/questions/29107928/swift-map-extension-for-set
Even this does not compile:
extension IntSet {
func aFunction() -> Set<String> {
let array: [String] = self.map { "\($0)" }
print(array) // This prints correctly
let aSet = Set(array) // ERROR: No exact matches in call to initializer
return [] //Set(array) // No error here
}
}
If you work on array, no issue
typealias IntSet = [Int] //Set<Int>
extension IntSet {
func aFunction() -> Set<String> {
let array: [String] = self.map { "\($0)" }
return Set(array)
}
}
I tried what is proposed in the referenced link, to no avail.
extension Set {
/// Map, but for a `Set`.
/// - Parameter transform: The transform to apply to each element.
func map<T>(_ transform: (Element) throws -> T) rethrows -> Set<T> {
var tempSet = Set<T>()
try forEach {
tempSet.insert(try transform($0))
}
return tempSet
}
}
I got it working by building the set manually
extension IntSet {
func aFunction() -> Set<String> {
var set3: Set<String> = []
for s in self {
set3.insert(String(s))
}
return set3
}
}
But building from an array did not work…
extension IntSet {
func aFunction() -> Set<String> {
var array2: [String] = []
for s in self {
array2.append(String(s))
}
return Set(array2) // Cannot convert return expression of type 'Set<Int>' to return type 'Set<String>'
}
}