Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding map to Range in Swift

Tags:

generics

swift

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.

like image 952
fabian789 Avatar asked Sep 07 '25 12:09

fabian789


1 Answers

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.

like image 176
mluisbrown Avatar answered Sep 09 '25 18:09

mluisbrown