Swift中的可选值是什么? [英] What is an optional value in Swift?
问题描述
从 Apple的文档:
您可以使用
if
和let
在一起使用可能缺少的值。这些值表示为可选。可选值包含一个值或包含nil
以指示该值缺失。在值的类型后面写一个问号(?
)以将该值标记为可选。
为什么要使用可选值?
Swift中的可选项是一个变量保持值或无值。可选项是通过在类型中添加?
来编写的:
var myOptionalString :串? =Hello
Swift还引入了可选类型,用于处理不存在的值。可选项说有一个值,它等于x或根本没有值。可选项类似于在Objective-C中使用带有指针的nil,但是它们适用于任何类型,而不仅仅是类。可选项比Objective-C中的nil指针更安全和更具表现力,并且是许多Swift最强大功能的核心。
可选项是一个事实的例子,Swift是一种类型安全的语言。 Swift帮助你清楚你的代码可以使用的值的类型。如果你的代码的一部分期望一个字符串,类型安全防止你传递它一个错误。
有些地方可选项是非常有用的:
- 当属性可以存在或不存在时,例如
middleName
或在
Person
类 中 - 当方法可以返回值或没有返回值时,匹配数组
- 当方法返回结果或返回错误并且不返回任何值时
- 委托属性
-
weak
类中的属性。他们指向的东西可以设置为nil
- 对于可能必须被释放以回收内存的大型资源
EDIT:以下段落使用可选字符作为布尔值适用于早期版本的Swift,现在你需要使用如果let myString = myString
给出的速记。 您不能使用可选作为布尔
键入任何
一个可选的布尔
类型在如果
或 while
声明。下面是一个创建可选项,然后检查其存在的示例:
var myString:String? =Hello
if myString {
println(myString)
}
如果你尝试使用非可选类型,它会给出一个编译器错误:Type'String'不符合协议'LogicValue'
var myOtherString:String =Hello
if myOtherString {//错误
println(myOtherString)
}
此外,如果您尝试将非可选属性设置为 nil
您会收到错误无法找到接受所提供的参数__conversion的重载:
var myOtherString:String = nil //错误
如果一个变量被声明为可选的,可以 nil
。事实上,所有可选项都以 nil
开头,直到它们设置为:
var possibleString:String? =Hello
possibleString = nil
如果可能String {
println(It's not nil)
}
以下是使用可选项的一种方法:
var nameString:String? =Zed//也可以是nil
如果nameString {
println(\(nameString)'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)在字典中)
}
有一个检查值是否存在的简写,然后用它做一些事情。您可以从此样式进行转换:
let possibleName:String? = users [ballmer]
如果可能Name {
let foundName = possibleName! //使用解包运算符强制输出值(!)
println(Name:\(foundName))
}
...对此简写,如果
possibleName
有一个值,则解开它并将其值设置为foundName
。if let foundName = possibleName {
println :\(foundName))
}
您使用感叹号!注意,打开一个可选的
nil
会导致崩溃,总是请在打开之前检查值是否存在://崩溃:致命错误:无法解开可选。
let name = possibleName!
Swift指南的更多信息:
在if语句中,条件必须是布尔表达式 - 这意味着代码如
if score { ...}
您可以使用if和let一起使用可能缺少。这些值表示为可选。可选值包含值或包含nil以指示该值缺失。在值类型后面写一个问号(?)以将该值标记为可选。
Objective-C中的同样的事情:
NSString * myString = @Hello;
if(myString){
NSLog(@%@,myString);
}
Objective-C更宽松的是什么, (
NO
,0
,nil
)。 Swift更具限制性,想要一个布尔值(或者解开为布尔值)。使用可选项也可以消除对NSNotFound
和使用-1
表示假的需要。
更多资源:
- Swift编程指南
- 在Swift中可选的(中)
- WWDC会议402Swift简介(大约从14:15开始)
诗从1899关于可选:
昨天在楼梯上
我遇到一个不在的人
他今天不在那里
我希望他会走了
From Apple's documentation:
You can use
if
andlet
together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or containsnil
to indicate that the value is missing. Write a question mark (?
) after the type of a value to mark the value as optional.Why would you want to use an optional value?
解决方案An optional in Swift is a variable that can hold either a value or no value. Optionals are written by appending a
?
to the type:var myOptionalString:String? = "Hello"
From "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.
Some places optionals are useful:
- When a property can be there or not there, like
middleName
orspouse
in aPerson
class - When a method can return a value or nothing, like searching for a match in an array
- When a method can return either a result or get an error and return nothing
- Delegate properties (which don't always have to be set)
- For
weak
properties in classes. The thing they point to can be set tonil
- For a large resource that might have to be released to reclaim memory
EDIT: The following paragraphs using optionals as booleans applies to an earlier version of Swift, nowadays you need to use the shorthand given with if let myString = myString
. You can not use an optional as a Boolean
type any more
You can use an optional as a Boolean
type in an if
or while
statement. Here's an example of creating an optional, then checking for its existence:
var myString:String? = "Hello"
if myString {
println(myString)
}
If you try to do this using a non-optional type it will give a compiler error: "Type 'String' does not conform to protocol 'LogicValue'"
var myOtherString:String = "Hello"
if myOtherString { // Error
println(myOtherString)
}
Also, if you try to set a non-optional to nil
you get the error "Could not find an overload for '__conversion' that accepts the supplied arguments":
var myOtherString:String = nil // Error
If a variable is declared as an optional, it can be nil
. In fact all optionals start with a value of nil
until they are set to something:
var possibleString:String? = "Hello"
possibleString = nil
if possibleString {
println("It's not nil")
}
Here's one way to use optionals:
var nameString:String? = "Zed" // could also be nil
if nameString {
println("\(nameString)'s alive")
} else {
println("Zed's dead")
}
You can use optionals for checking the existence of a value in a dictionary:
let users = [ "sjobs" : "Steve Jobs", "bgates" : "Bill Gates"]
let steve: String? = users["sjobs"]
if steve { // if steve != nil
println("\(steve) is in the dictionary")
}
There's a shorthand for checking whether a value exists, then doing something with it. You can convert from this style:
let possibleName: String? = users["ballmer"]
if possibleName {
let foundName = possibleName! // Force out value with unwrap operator (!)
println("Name: \(foundName)")
}
...to this shorthand, which says "If possibleName
has a value, unwrap it and set its value to foundName
.
if let foundName = possibleName {
println("Name: \(foundName)")
}
You use an exclamation mark "!" to unwrap the optional. You can't use an optional for much (except checking its nilness) until it's unwrapped. Note that unwrapping an optional that's nil
will cause a crash. Always check that a value exists before unwrapping:
// Crash: fatal error: Can't unwrap Optional.
let name = possibleName!
More from the Swift guide:
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.
It may be helpful to see the same thing in Objective-C:
NSString *myString = @"Hello";
if (myString) {
NSLog(@"%@", myString);
}
Objective-C is more lenient about what it will allow to mean "false" (NO
, 0
, nil
). Swift is more restrictive and wants a boolean (or something which "unwraps" to a boolean). Using optionals also gets rid of the need for stuff like NSNotFound
and using -1
to represent false.
More resources:
- The Swift Programming Guide
- Optionals in Swift (Medium)
- WWDC Session 402 "Introduction to Swift" (starts around 14:15)
To finish, here's a poem from 1899 about optionals:
Yesterday upon the stair
I met a man who wasn’t there
He wasn’t there again today
I wish, I wish he’d go away
Antigonish
这篇关于Swift中的可选值是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!