相关疑难解决方法(0)

在Swift中使用可选值

在阅读The Swift Programming Language时,我遇到了这个片段:

您可以使用iflet一起使用可能缺少的值.这些值表示为选项.可选值包含值或包含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在这种情况下,确切的作用是什么?

我确实看过这个页面,但还是有点困惑.

cocoa ios swift

3
推荐指数
1
解决办法
1417
查看次数

在这种情况下,为什么我必须显式解包我的字符串?

我有一个字符串var oneString: String!,后来在一个方法中,当我想连接一个字符串,oneString我必须这样做:

oneString! += anyString
Run Code Online (Sandbox Code Playgroud)

如果我不添加,!我会收到错误'String!' is not identical to 'CGFloat'

如果我初始化我的字符串var oneString = ""我没有这个问题.为什么?为什么我需要打开,oneString而我明确表示在我宣布它时它不会是零?

swift

3
推荐指数
1
解决办法
389
查看次数

Swift:貌似不允许比较String?用字符串?

我要求用户输入(这工作)并尝试输出不同的结果取决于输入是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)

compare switch-statement optional swift

1
推荐指数
1
解决办法
1666
查看次数

感叹号在Swift方法的头部的数据类型中的含义是什么

我注意到了一些方法,主要是在协议中有一个!在他们的参数.例如来自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)

究竟意味着什么!在这种背景下?

swift

0
推荐指数
1
解决办法
373
查看次数

标签 统计

swift ×4

cocoa ×1

compare ×1

ios ×1

optional ×1

switch-statement ×1