在阅读The Swift Programming Language时,我遇到了这个片段:
您可以使用if和let一起使用可能缺少的值.这些值表示为选项.可选值包含值或包含nil以指示缺少值.在值的类型后面写一个问号(?)以将值标记为可选.
// Snippet #1
var optionalString: String? = "Hello"
optionalString == nil
// Snippet #2
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
Run Code Online (Sandbox Code Playgroud)
Snippet#1足够清晰,但是在Snippet#2中发生了什么?有人可以分解并解释吗?它只是使用if - else块的替代方案吗?let在这种情况下,确切的作用是什么?
我确实看过这个页面,但还是有点困惑.
我有一个字符串var oneString: String!,后来在一个方法中,当我想连接一个字符串,oneString我必须这样做:
oneString! += anyString
Run Code Online (Sandbox Code Playgroud)
如果我不添加,!我会收到错误'String!' is not identical to 'CGFloat'
如果我初始化我的字符串var oneString = ""我没有这个问题.为什么?为什么我需要打开,oneString而我明确表示在我宣布它时它不会是零?
我要求用户输入(这工作)并尝试输出不同的结果取决于输入是nil,空字符串,还是使用switch子句的非空字符串(不起作用).
第一次尝试给我一个错误,因为我试图将可选字符串与非可选字符串进行比较:
import Foundation
print("Hi, please enter a text:")
let userInput = readLine(stripNewline: true)
switch userInput {
case nil, "": // Error: (!) Expression pattern of type ‘String’ cannot match values of type ‘String?’
print("You didn’t enter anything.")
default:
print("You entered: \(userInput)")
}
Run Code Online (Sandbox Code Playgroud)
很公平,所以我创建一个可选的空字符串来比较:
import Foundation
print("Hi, please enter a text:")
let userInput = readLine(stripNewline: true)
let emptyString: String? = "" // The new optional String
switch userInput {
case nil, emptyString: // Error: (!) Expression …Run Code Online (Sandbox Code Playgroud) 我注意到了一些方法,主要是在协议中有一个!在他们的参数.例如来自UIImagePickerControllerDelegate的这些:
protocol UIImagePickerControllerDelegate : NSObjectProtocol {
@optional func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!)
@optional func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: NSDictionary!)
@optional func imagePickerControllerDidCancel(picker: UIImagePickerController!)
}
Run Code Online (Sandbox Code Playgroud)
究竟意味着什么!在这种背景下?