我想引用具有特定类型的枚举对象,而不仅仅是泛型AnyObject!
,但在文档中找不到有关它的任何信息.
enumerateObjectsUsingBlock
Swift中的签名是:
func enumerateObjectsUsingBlock(_ block: ((AnyObject!,
Int,
UnsafePointer<ObjCBool>) -> Void)!)
Run Code Online (Sandbox Code Playgroud)
在目标C中:
- (void)enumerateObjectsUsingBlock:(void (^)(id obj,
NSUInteger idx,
BOOL *stop))block
Run Code Online (Sandbox Code Playgroud)
如果我想将迭代的对象视为特定类型,则在Objective CI中只需动态调整签名,例如:
[array enumerateObjectsUsingBlock:^(NSString *s, NSUInteger idx, BOOL *stop){
// ...some function of s as NSString, not just id...
}];
Run Code Online (Sandbox Code Playgroud)
如何在Swift中获得此行为?
在Swift中你不能像在Objective-C中那样"调整"块/闭包签名,你必须明确地进行转换.使用可选的强制转换:
array.enumerateObjectsUsingBlock({ object, index, stop in
if let str = object as? String {
println(str)
}
})
Run Code Online (Sandbox Code Playgroud)
如果您确定所有对象都是字符串,则使用强制转换:
array.enumerateObjectsUsingBlock({ object, index, stop in
let str = object as String // `as!` in Swift 1.2
println(str)
})
Run Code Online (Sandbox Code Playgroud)
由于NSArray
桥接Array
无缝,您可以使用Array
枚举:
for str in array as [String] {
println(str)
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要元素及其索引:
for (index, str) in enumerate(array as [String]) {
println("\(index): \(str)")
}
Run Code Online (Sandbox Code Playgroud)
Swift 3.0的更新
用enumerateObjects(using:)
:
array.enumerateObjects(using: { (object, index, stop) in
if let str = object as? String {
print("\(index): \(str)")
}
})
Run Code Online (Sandbox Code Playgroud)
枚举为Swift数组:
if let a = array as? [String] {
for str in a {
print(str)
}
}
Run Code Online (Sandbox Code Playgroud)
将元素和索引枚举为Swift数组:
if let a = array as? [String] {
for (index, str) in a.enumerated() {
print("\(index): \(str)")
}
}
Run Code Online (Sandbox Code Playgroud)