Adding Map to Range in Swift
I am trying to expand Range
with a map
similar function 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
defined Range
:
struct Range<Element : ForwardIndexType> : …
I thought it looked 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 closing closure, not the passed one map
.
Also, changing the second line above to
return (0...42 as Range<Int>).map {
gets rid of the error.
I don't understand this as my function map
should return [String?]
in both cases. And in general, I would suggest that 0...42
there is Range<Int>
also no broadcast.
I am using Swift 2.0.
source to share