Swift中的泛型

克洛伊

尝试理解下面的代码。我知道在实例化Optional时会传递T,就像在Optional中一样,但是映射中的U类型呢。那是什么类型?

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
} 
mattjgalloway

类型Uf参数到map函数。因此,如果传递的闭包返回a Int,则map返回a Int?如果传递的闭包返回a Array<Int>,则map返回a Array<Int>?

例如,尝试以下操作:

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

您会发现这opt1Int?opt2String?

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章