Swift心得笔记之集合类型

2020-01-08 22:44:23丽君

    if let number = someNumber {
        return number + 1
    } else {
        return nil
    }
}
increment(5)   // Some 6
increment(nil) // nil

 

我们也可以用 map 来实现:

 

复制代码
func increment(someNumber: Int?) -> Int? {
    return someNumber.map { number in number + 1 }
}

 

increment(5)   // Some 6
increment(nil) // nil

 

包括其他可选类型也是可行的,比如 String :

 

复制代码
func hello(someName: String?) -> String? {
    return someName.map { name in "Hello, (name)"}
}
hello("NatashaTheRobot") // Some "Hello, NatashaTheRobot"
hello(nil) // nil

 

再搭配上 ?? 符号,嗯基本够用了:

 

复制代码
func hello(someName: String?) -> String {
    return someName.map { name in "Hello, (name)" } ?? "Hello world!"
}

 

hello("NatashaTheRobot") // "Hello, NatashaTheRobot"
hello(nil)               // "Hello world!"

 

扩展

数组和字典十分常用,而官方的方法功能有限。我们可以学习ExSwift 中 Array.swift 的内容,给 Array 添加一些 Extension。

以上所述就是本文的全部内容了,希望大家能够喜欢。



注:相关教程知识阅读请移步到swift教程频道。