enumerateObjectsUsingBlock in Swift

Foundation

enumerateObjectsUsingBlock: is not a method on Array but on NSArray. If you want to use it you’ll need an instance of NSArray rather than Array.

import Foundation

var array: NSArray = ["Some", "strings", "in", "an", "array"]

array.enumerateObjectsUsingBlock({ object, index, stop in
    //your code
})

if you have an existing array, you can cast a swift Array to an NSArray using as

var cocoaArray = swiftArray as NSArray

or if you simply import Foundation the Swift compiler will automatically bridge your Swift array to an NSArray and all the NSArray methods will become available for you.

Swift 1

or you can just use Swift’s enumerate function:

for (index, value) in enumerate(array) {
    // your code
}

Swift 2

In Swift 2, enumerate is no longer a free function, now it’s in a protocol extension!

for (index, value) in array.enumerate() {
    // your code
}

Swift 3

And in Swift 3, enumerate was renamed to enumerated

for (index, value) in array.enumerated() {
    // your code
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)