Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic within a generic in Swift

Tags:

swift

Trying to make sense of the code below. I understand that T is passed by when instantiating the Optional, as in Optional, but what about the U type in map. What type does that assume?

enum Optional<T> : LogicValue, Reflectable {
    case None
    case Some(T)
    init()
    init(_ some: T)

    /// Allow use in a Boolean context.
    func getLogicValue() -> Bool

    /// Haskell's fmap, which was mis-named
    func map<U>(f: (T) -> U) -> U?
    func getMirror() -> Mirror
} 
like image 396
Chloe Avatar asked Jun 24 '14 19:06

Chloe


2 Answers

The type U comes from the f parameter to the map function. So if you pass a closure that returns a Int, then map returns a Int?. If you pass a closure that returns a Array<Int>, then map returns a Array<Int>?.

For example, try this:

var opt1: Optional<Int> = .Some(1)
var opt2 = opt1.map { (i: Int) -> String in return "String: \(i)" }

You'll find that opt1 is an Int? and opt2 is a String?.

like image 187
mattjgalloway Avatar answered Oct 10 '22 13:10

mattjgalloway


When calling the map function the caller must provide a single argument which is a closure that:

  1. Has a single argument that is the same type as the one used to instantiate Optional, i.e. T
  2. Has a return value of some type.

U will then be the type of said return value.

like image 21
Cezar Avatar answered Oct 10 '22 14:10

Cezar