Swift语法中的"as"有什么功能?

chr*_*phe 4 swift

最近,我偶然发现了一个语法,我不能找到一个参考:什么在雨燕的语法是什么意思?

像:

var touch = touches.anyObject() as UITouch!
Run Code Online (Sandbox Code Playgroud)

不幸的是,这是很难寻找像一个字作为,所以我并没有在苹果雨燕编程语言的手册中找到它.也许有人可以引导我到正确的段落?

又为何之后元素作为始终有一个!表示打开一个可选的?

谢谢!

Ast*_*oCB 5

as关键字用于将对象转换为另一种类型的对象.为此,该类必须可转换为该类型.

例如,这有效:

let myInt: Int = 0.5 as Int // Double is convertible to Int
Run Code Online (Sandbox Code Playgroud)

但是,这不是:

let myStr String = 0.5 as String // Double is not convertible to String
Run Code Online (Sandbox Code Playgroud)

您还可以if-let?运算符执行可选的转换(通常在语句中使用):

if let myStr: String = myDict.valueForKey("theString") as? String {
    // Successful cast
} else {
    // Unsuccessful cast
}
Run Code Online (Sandbox Code Playgroud)

在你的情况下,touches是(我假设从anyObject()电话中)a NSSet.因为NSSet.anyObject()返回一个AnyObject?,你必须将结果UITouch转换为能够使用它.

在该示例中,如果anyObject()返回nil,则应用程序将崩溃,因为您正在强制执行转换UITouch!(显式解包).更安全的方式是这样的:

if let touch: UITouch = touches.anyObject() as? UITouch {
  // Continue
}
Run Code Online (Sandbox Code Playgroud)