【发布时间】:2015-03-02 19:01:00
【问题描述】:
我一直在阅读Functional Programming in Swift 这本书,但我真的没有很好的方法来理解可选章节中介绍的概念的差异。
使用可选项时的模式往往是:
if let thing = optionalThing {
return doThing(thing)
}
else {
return nil
}
这个成语用标准库函数map简洁处理
map(optionalThing) { thing in doThing(thing) }
然后这本书继续介绍了可选绑定的概念,这是我区分能力开始崩溃的地方。
本书指导我们定义map函数:
func map<T, U>(optional: T?, f: T -> U) -> U?
{
if let x = optional {
return f(x)
}
else {
return nil
}
}
并且还指导我们定义一个可选的绑定函数。 注意:本书使用运算符>>=,但我选择使用命名函数,因为它可以帮助我看到相似之处。
func optionalBind<T, U>(optional: T?, f: T -> U?) -> U?
{
if let x = optional {
return f(x)
}
else {
return nil
}
}
这两种方法的实现在我看来都是一样的。两者之间的唯一区别是它们采用的函数参数:
-
map接受一个将 T 转换为 U 的函数 -
optionalBind接受一个将 T 转换为可选 U 的函数
“嵌套”这些函数调用的结果伤了我的脑筋:
func addOptionalsBind(optionalX: Int?, optionalY: Int?) -> Int?
{
return optionalBind(optionalX) { x in
optionalBind(optionalY) { y in
x + y
}
}
}
func addOptionalsMap(optionalX: Int?, optionalY: Int?) -> Int?
{
return map(optionalX) { x in
map(optionalY) { y in
x + y
}
}
}
-
addOptionalsBind函数完全符合您的预期。 -
addOptionalsMap函数编译失败,说明:'Int??'不能转换为 'Int?'
【问题讨论】:
标签: swift