Swift基础

Swift 可选(Optional ?& !)类型介绍

2018-12-27  本文已影响0人  咸鱼Boss
enum Optional<Wrapped>

官方原文(https://developer.apple.com/documentation/swift/optional)
在swift中我们常常看到 !? 符号其实这是Swift特有一个类:可选类型(optional)。可选类型类似于Objective-C中指针的nil值,在 Objective-C 中 object 的值可以设为 nil, 但是在 Swift 当中这是不可以的。也就是说:

var optionalInteger: Int = nil  //这种写法不合法

Int 和 Int?其实不是同个类
Int 是 “整数” 而 Int?是 “可选”

//下面两行代码作用是一样的可以互换
var optionalInteger: Int?
var optionalInteger: Optional<Int>

在Swift中可以使用 optional 来代替 Objective-C 中的 nil
可选(optional)可以用来表示一个optional<类>中的类有值并且是x,或者没有值类似于nil。

例子:

var optionalInteger: Int?
//以下代码返回“nil”
if let value = optionalInteger{
    print(value)
}else{
    print("nil")
}
//以下代码返回“1”
optionalInteger = 1
if let value = optionalInteger{
    print(value)
}else{
    print("nil")
}

那么为什么Swift需要Optional呢?

原文出自(https://www.quora.com/Why-does-Swift-have-optionals

In Objective-C, nil is a valid value for each and every object reference. Unfortunately, some code may not accept it. For example, and largely for historical reasons, the Foundation collection classes such as NSArray cannot store nil and will throw an exception at runtime if you try.

For nil to be dealt with safely, therefore, the programmer mustn’t be able to pass nil into NSArray’s -addObject: method. Instead, an object reference which might be nil must be unpacked to discover whether it is a valid reference or not, and if so, the valid reference can be added to the array.

翻译:
Optional 相较于 Objective-C中的 nil 更为安全

在 Objective-c中, nil 可以背合法的适用于所有类的 reference 但是这样的做法并不被所有的代码接受。比如说 NSArray 不能储存 nil 类型,如果在 runtime 存入 nil 会 throw exception。
可选(optional)就不存在这一问题。所有的可选在使用时都会被unpack 并检查是否合法。只有合法的可以存入NSArray,并不会产生exception。


可选(optional)的常见使用方法分析

//因为 swift 不支持变量为 nil 所以必须用 optional
var optionalInteger: Int?
//使用 !来读取 optionalInteger的值,若 optional 为 non-nil
optionalInteger = 33
print(optionalInteger!)
class Animal {}
class Dog: Animal {
    var name = "CoCo"
}
class Cat: Animal{}

//强转成子类
let a: Animal = Dog()
a as! Dog
//不需要强转
a as Animal


let dog: Dog? = nil
dog?.name       // evaluates to nil
dog!.name       // triggers a runtime error

let animal: Animal = Cat()
animal as? Dog  // evaluates to nil
animal as! Dog  // triggers a runtime error
//如果有值显示具体的值如果没值显示“nil”
if let name = dog?.name{
    print(name)
}else{
    print("nil")
}
func findApt (aptNumber : String, aptNumbers: String[]) -> String? {
    for tempAptNumber in aptNumbers {
        if ( tempAptNumber == aptNumber) {
            return aptNumber
        }
    }
    return nil
}

希望本文能够帮助到你!

上一篇 下一篇

猜你喜欢

热点阅读