SaltyNuts SaltyNuts -4 years ago 180
Swift Question

enumerateObjectsUsingBlock - casting parameters in Swift

I want to refer to enumerated objects with their specific type, instead of just a generic

AnyObject!
, but cannot find any information about it in the docs.

The signature of
enumerateObjectsUsingBlock
in Swift is:

func enumerateObjectsUsingBlock(_ block: ((AnyObject!,
Int,
UnsafePointer<ObjCBool>) -> Void)!)


and in Objective C:

- (void)enumerateObjectsUsingBlock:(void (^)(id obj,
NSUInteger idx,
BOOL *stop))block


If I want to treat the objects that are iterated over as a specific type, in Objective C I simply adjust the signature on the fly, for example:

[array enumerateObjectsUsingBlock:^(NSString *s, NSUInteger idx, BOOL *stop){
// ...some function of s as NSString, not just id...
}];


How do I get this behaviour in Swift?

Answer Source

In Swift you cannot "tweak" the block/closure signature as in Objective-C, you have to cast explicitly. Either with an optional cast:

array.enumerateObjectsUsingBlock({ object, index, stop in
    if let str = object as? String {
        println(str)
    }
})

or with a forced cast if you are sure that all objects are strings:

array.enumerateObjectsUsingBlock({ object, index, stop in
    let str = object as String // `as!` in Swift 1.2
    println(str)
})

Since NSArray bridges to Array seamlessly, you can alternatively use the Array enumeration:

for str in array as [String] {
    println(str)
}

or, if you need the elements together with their index:

for (index, str) in enumerate(array as [String]) {
    println("\(index): \(str)")
}

Update for Swift 3.0

With enumerateObjects(using:):

array.enumerateObjects(using: { (object, index, stop) in
    if let str = object as? String {
        print("\(index): \(str)")
    }
})

Enumerate as Swift array:

if let a = array as? [String] {
    for str in a {
        print(str)
    }
}

Enumerate elements and indices as Swift array:

if let a = array as? [String] {
    for (index, str) in a.enumerated() {
        print("\(index): \(str)")
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download