加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

可可 – Swift中的可选值是什么?

发布时间:2020-12-14 06:20:28 所属栏目:百科 来源:网络整理
导读:从 Apple’s documentation: You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that the value is missi
从 Apple’s documentation:

You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value as optional.

为什么要使用可选值?

Swift中的可选属性是一个可以保存值或无值的变量。可选项是通过附加一个?到类型:
var myOptionalString:String? = "Hello"

从“The Basics” in the Swift Programming Language:

Swift also introduces optional types,which handle the absence of a value. Optionals say either “there is a value,and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C,but they work for any type,not just classes. Optionals are safer and more expressive than nil pointers in Objective-C and are at the heart of many of Swift’s most powerful features.

Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String,type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process.

有些地方可选择是有用的:

>当一个属性可以存在或没有,像middleName或配置在Person类中
>当一个方法可以返回一个值或什么也不做,例如在数组中搜索匹配
>当一个方法可以返回一个结果或得到一个错误,并什么也不返回
>委托属性(并不总是必须设置)
>对于类中的弱属性。他们指向的东西可以设置为零
>对于可能必须被释放以回收内存的大型资源

编辑:以下段落使用可选的布尔类型适用于早期版本的Swift,现在你需要使用给出的简写if let myString = myString。您不能再使用可选作为布尔类型

您可以在if或while语句中使用可选作为布尔类型。下面是一个创建可选项,然后检查其存在的示例:

var myString:String? = "Hello"

if myString {
    println(myString)
}

如果你尝试使用非可选类型,它将给出一个编译器错误:“类型’字符串’不符合协议’LogicValue’”

var myOtherString:String = "Hello"

if myOtherString { // Error
    println(myOtherString)
}

此外,如果您尝试将非可选设置为nil,您会收到错误“无法为接受提供的参数的__conversion找到重载”:

var myOtherString:String = nil // Error

如果一个变量被声明为可选的,它可以是nil。事实上,所有可选项都以nil值开始,直到它们被设置为:

var possibleString:String? = "Hello"
possibleString = nil

if possibleString {
    println("It's not nil")
}

这里有一种使用可选项的方法:

var nameString:String? = "Zed" // could also be nil

if nameString {
    println("(nameString)'s alive")
} else {
    println("Zed's dead")
}

您可以使用可选字段来检查字典中是否存在值:

let users = [ "sjobs" : "Steve Jobs","bgates" : "Bill Gates"]

let steve: String? = users["sjobs"]
if steve { // if steve != nil
    println("(steve) is in the dictionary")
}

有一个检查值是否存在的简写,然后用它做一些事情。您可以从此样式转换:

let possibleName: String? = users["ballmer"]

if possibleName {
    let foundName = possibleName! // Force out value with unwrap operator (!)
    println("Name: (foundName)")
}

…到这个简写,它说“如果可能的名称有一个值,解开它,并将其值设置为foundName。

if let foundName = possibleName {
    println("Name: (foundName)")
}

您使用感叹号“!”解包可选。你不能使用可选的很多(除非检查它的nilness),直到它被解开。注意,打开一个可选的nil将导致崩溃。在展开前始终检查值是否存在:

// Crash: fatal error: Can't unwrap Optional.
let name = possibleName!

更多从Swift指南:

In an if statement,the conditional must be a Boolean expression—this means that code such as if score { ... } is an error,not an implicit comparison to zero.

You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value as optional.

在Objective-C中看到同样的事情可能会有所帮助:

NSString *myString = @"Hello";
if (myString) {
    NSLog(@"%@",myString);
}

Objective-C对于它将允许什么意思是“假”(NO,0,nil)更宽松。 Swift更具限制性,需要一个布尔值(或者“展开”为布尔值)。使用可选项也摆脱了对像NSNotFound和使用-1表示假的东西的需要。

更多资源:
– The Swift Programming Guide
– Optionals in Swift (Medium)
– WWDC Session 402 “Introduction to Swift” (starts around 14:15)

为了完成,这里有一首诗从1899年关于可选:

昨天在楼梯上
我遇到一个不在那里的男人
他今天不在那里
我希望他愿意离开
Antigonish

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读