I'm trying to extend Range with a map function similar to the one on Array:
extension Range {
func map<T>(@noescape transform: (Element) -> T) -> [T] {
var result = Array<T>()
for i in self {
result.append(transform(i))
}
return result
}
}
Element is defined by Range:
struct Range<Element : ForwardIndexType> : …
I thought this looked fairly good, however when using it I get a compiler error:
let cellSubtitles: [String?] = { // <-- Unable to infer closure type in the current context
return 0...42.map {
let week: Int = $0/7
switch week {
case 0: return nil
case 1: return "Last Week"
default: return "\(week) Weeks Ago"
}
}
}()
Note that the error is for the surrounding closure, not for the one passed to map.
Also, Changing the second line above to
return (0...42 as Range<Int>).map {
gets rid of the error.
I do not understand this as my map function should return [String?] in both cases. And anyways, I would have assumed that 0...42 is Range<Int> also without the cast.
I'm using Swift 2.0.
If you are using Swift 2.0 then map is already defined for Range since Range conforms to CollectionType, which implements map, so there is no need to define it yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With