当前位置: 代码迷 >> 综合 >> Day05:Optional
  详细解决方案

Day05:Optional

热度:73   发布时间:2023-09-29 18:38:08.0
  • Optional的存在
//OC 里的nil是无类型的指针。
//OC 里面的数组、字典、集合等不允许放入nil。
//OC 所有对象变量都可以为nil。
//OC 只能作用在对象上,而其他地方又用其特殊值(例如NSNotFound)表示值的缺失。
  • Optional的语法
//通过在变量类型后面加?表示:这里有一个值,他等于x或者这里根本没有值。
var nickName:String?
//你可以通过给可选变量赋值一个nil来将之设置为没有值。
nickName = nil
//在OC中nil上一个指向不存在对象的指针。在swift中nil不是指针,他是值缺失的一种特殊类型,任何类型的可选项都可以设置nil而不仅仅是对象类型。
  • Optional-if语句以及强制展开
//可选值没法直接使用,需要用!展开之后才能使用。
var shopName:String? = "巧克力"
if shopName != nil {let shopCount = shopName!.countprint(shopCount)//3
}
//使用!来获取一个不存在的可选值会导致运行错误,在使用!强制展开之前必须确保可选项中包含一个非nil的值。var nilName:String? = nil
//let nilNameTest = nickName! 非nil值
  • Optional-绑定
//可以使用可选项绑定来判断可选项是否包含值,如果包含就把值赋给一个临时的常量或者变量。
var eatName:String? = "巧克力"
if let item = eatName  {let eatCount = item.countprint(eatCount)//3
}
//可选绑定可以与if和while的语句使用来检查可选内部的值,并赋值给一个变量或常量。
let testNumber = Int("4")
while var item = testNumber,item > 2 {print("大于")item = 1
}
//同一个if语句中包含多个可选项,用逗号分隔开即可。如果任何一可选项绑定结果是nil或者布尔值为false,那么整个if判断会被看作false。
if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {print("\(firstNumber) < \(secondNumber) < 100")//4 < 42 < 100
}
  • Optional-隐式展开
//有些可选项一旦被设定值之后,就会一直拥有值,这种情况下,就可以去掉检查的需求,也不必每次访问的时候都进行展开。
//通过在声明的类型后边添加一个感叹号(String!)而非问号(String?)来书写隐式展开的可选项。
//隐式展开可选项主要被用在swift类的初始化过程中。
var str:String! = "abc"
let strCount = str.count
print(strCount)
  • Optional-可选链
//可选项后面加问号:如果可选项不为nil,返回一个可选项结果,否则返回nil。
var subStr:String? = "abc"
let subStrCount = subStr?.countif subStrCount != nil {let lastIndex = subStrCount! - 1print(lastIndex)//2
}
  • Optional-实现探究
//Optional其实是标注库里的一个enum类型。
@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.none就是nil,Optional.some则包装了实际的值。
var optionalStr:Optional<String> = "abc"if let item = optionalStr {let count = item.countprint(count)
}
  • 泛型属性unsafelyUnwrapped 
    /// The wrapped value of this instance, unwrapped without checking whether/// the instance is `nil`.////// The `unsafelyUnwrapped` property provides the same value as the forced/// unwrap operator (postfix `!`). However, in optimized builds (`-O`), no/// check is performed to ensure that the current instance actually has a/// value. Accessing this property in the case of a `nil` value is a serious/// programming error and could lead to undefined behavior or a runtime/// error.////// In debug builds (`-Onone`), the `unsafelyUnwrapped` property has the same/// behavior as using the postfix `!` operator and triggers a runtime error/// if the instance is `nil`.////// The `unsafelyUnwrapped` property is recommended over calling the/// `unsafeBitCast(_:)` function because the property is more restrictive/// and because accessing the property still performs checking in debug/// builds.////// - Warning: This property trades safety for performance.  Use///   `unsafelyUnwrapped` only when you are confident that this instance///   will never be equal to `nil` and only after you've tried using the///   postfix `!` operator.@inlinable public var unsafelyUnwrapped: Wrapped { get }//理论上我们可以直接调用unsafelyUnwrapped获得可选项的值var subTestStr:String? = "abc"
let countSubTestStr = subTestStr.underestimatedCount
print(countSubTestStr)