问题描述
下面是变量名yourname和yourname2的可选字符串的代码.
Below is the code for optional string for variable name yourname and yourname2.
实际上,它们之间有什么区别,以及在使用yourname2的情况下如何强制展开
Practically what is difference between them and how forced unwrapping in case of yourname2
var yourname:String?
yourname = "Paula"
if yourname != nil {
println("Your name is \(yourname)")
}
var yourname2:String!
yourname2 = "John"
if yourname2 != nil {
println("Your name is \(yourname2!)")
}
推荐答案
字符串?通常是可选的.它可以包含String或nil.
The String? is normal optional. It can contain either String or nil.
弦乐!是一个隐式解包的可选,其中您指示它在初始化后将始终具有一个值.
The String! is an implicitly unwrapped optional where you indicate that it will always have a value - after it is initialized.
您的情况下,您的名字是可选的,您的名字2!不是.您的第一个打印语句将输出类似您的名称为Optional("Paula")"
yourname in your case is an optional, yourname2! isn't.Your first print statement will output something like "Your name is Optional("Paula")"
您的第二条打印语句将输出类似您的名字叫约翰"的字样.如果从语句中删除感叹号,它将打印相同的内容.
Your second print statement will output something like "Your name is John". It will print the same if you remove the exclamation mark from the statement.
顺便说一句,在iBooks上免费提供了Swift文档作为"The Swift Programming Language",最新的版本也是在此处在线.
By the way, Swift documentation is available as "The Swift Programming Language" for free on iBooks and the very latest is also online here.
这篇关于可选和强制展开之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!