考虑这个myFilter
函数,它接受泛型参数并根据谓词过滤数组.这与filter()
Swift提供的功能相同.
func myFilter<T>(source: [T], predicate:(T) -> Bool) -> [T] {
var result = [T]()
for i in source {
if predicate(i) {
result.append(i)
}
}
return result
}
Run Code Online (Sandbox Code Playgroud)
这有什么不同,
func myFilter(source: [AnyObject], predicate:(AnyObject) -> Bool) -> [AnyObject] {
var result = [AnyObject]()
for i in source {
if predicate(i) {
result.append(i)
}
}
return result
}
Run Code Online (Sandbox Code Playgroud)
即使在后一个例子中,我们也不是达到了泛型的地步吗?
我正在键入一些Swift代码,因为我很无聊并且一段时间没有编写Swift.
当我包含UIKit时,为什么这段代码有用呢?
import UIKit
public class foo {
private var boolTest : Bool?
init() {
boolTest = true
}
public func call() -> AnyObject? {
if let bool = boolTest {
return bool
}
else {
return nil
}
}
}
foo().call()
Run Code Online (Sandbox Code Playgroud)
当我导入Darwin而不是UIKit时,它不起作用.
import Darwin
public class foo {
private var boolTest : Bool?
init() {
boolTest = true
}
public func call() -> AnyObject? {
if let bool = boolTest {
return bool
}
else {
return nil
} …
Run Code Online (Sandbox Code Playgroud)