美文网首页
二、Swift学习之Optional类型

二、Swift学习之Optional类型

作者: Hello_kid | 来源:发表于2020-10-19 23:12 被阅读0次

定义

在OC中没有Optional的概念

OC中的nil是一个指向不存在对象的指针

Swift中,nil不是指针,值缺失的一种特殊类型,任何类型的可选项都可以设置成nil而不仅仅是对象类型

通过在变量类型后面加表示

let name: String?

  • 表明name可能有值,也可能没有值

使用

可选项是不能直接使用的,

需要使用展开之后才能使用 (意思是确定这个变量里一定有值)

var str: String? = "abc"
// 强制展开
let count = str!.count 
//更安全的做法
if str != nil {
  let count = str!.count
}
//可选绑定
if let countStr = str {
  let count = countStr.count
}
// 隐式展开
var str: String! = "abc"

可选链

var str: String? = "abc"
let count = str?.count
// count也是一个可选项类型
//let lastIndex = count - 1 直接使用count会报错
if c = count {
  print(c)
}

如果不强制展开可选项,也不使用可选绑定 、隐式展开, 直接使用可选项加问号去掉用方法或者属性, 如果这个可选项不为空,返回的结果也是一个可选项类型,如果为空,返回的是一个nil,也需要区做对应的展开才能使用;

Optional实现原理

var st: Optional<String> = "abc" 
//  相当于 var st: String? = "abc"

通过Optional 类型可知

@frozen public enum Optional<Wrapped> : ExpressibleByNilLiteral {

    /// The absence of a value.
    ///
    /// In code, the absence of a value is typically written using the `nil`
    /// literal rather than the explicit `.none` enumeration case.
    case none

    /// The presence of a value, stored as `Wrapped`.
    case some(Wrapped)

    /// Creates an instance that stores the given value.
    public init(_ some: Wrapped)

Optional是一个公有的枚举类型,范型是Wrappedcase none代表没有值,case some(Wrapped) 存储的具体值;

var str: Optional<String> = "abc" 
//  相当于 var st: String? = "abc"
// 也可以使用可选绑定使用
if let actualStr = str {
    let cou = actualStr.count
    print(cou)
}
 @inlinable public var unsafelyUnwrapped: Wrapped { get }

这个属性里存储的实际的值

var str: Optional<String> = "abc" 
if str != nil {
    let cou = str.unsafelyUnwrapped.count
    print(cou)
}

相关文章

网友评论

      本文标题:二、Swift学习之Optional类型

      本文链接:https://www.haomeiwen.com/subject/eqqrmktx.html