swift中的enumerateObjectsUsingBlock

时间:2014-06-09 12:16:29

标签: swift

我正在尝试使用enumerateObjectsUsingBlock迭代数组以获取数据。 如何在Swift中使用enumerateObjectsUsingBlock?请帮我举个例子。

4 个答案:

答案 0 :(得分:55)

粉底

enumerateObjectsUsingBlock:不是Array上的方法,而是NSArray上的方法。如果你想使用它,你需要一个NSArray而不是Array的实例。

import Foundation

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

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

如果您有现有数组,则可以使用Array

快速NSArray投射到as
var cocoaArray = swiftArray as NSArray

或者如果您只是import Foundation,Swift编译器会自动将您的Swift数组桥接到NSArray,并且所有NSArray方法都可供您使用。

Swift 1

或者您可以使用Swift的enumerate功能:

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

Swift 2

在Swift 2中,enumerate不再是免费功能,现在它已经在协议扩展中了!

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

Swift 3

在Swift 3中,enumerate已重命名为enumerated

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

答案 1 :(得分:9)

新的枚举函数返回一个带有索引器和值的元组,因此您可以获得与enumerateObjectsUsingBlock类似的功能。

func myBlock (index: Int, value: Int, inout stop: Bool) -> Void {
    println("Index: \(index) Value: \(value)")
    if index == 3 {
        stop = true
    }
}

var array = [1,2,3,4,5]

for (index, value) in enumerate(array) {
    var stop = false;
    myBlock(index, value, &stop)
    if stop  {
        break;
    }
}

//Output...
//Index: 0 Value: 1
//Index: 1 Value: 2
//Index: 2 Value: 3
//Index: 3 Value: 4

我想他们没有公开enumerateObjectsUsingBlock,因为您可以使用上面的代码复制功能。

编辑:匿名函数崩溃了我的游乐场,因此使用了内联函数。还使用停止变量添加以用于说明目的。

答案 2 :(得分:1)

我写了CollectionType的扩展名。

Any way to stop a block literal in swift

    func forEach(body: ((Self.Generator.Element, Int, inout Bool) -> Void)) {
        var stop = false
        let enumerate = self.enumerate()
        for (index,value) in enumerate {
            if stop { break }
            body(value,index,&stop)
        }
    }

答案 3 :(得分:1)

现有答案可以解决问题中提出的问题。 另外,您可以为Array类编写扩展,并添加与-

类似的方法
extension Array{
func enumerateObject(_ block : (Any, Int,inout Bool)-> Void){
    var stop = false
    for (index, aValue) in self.enumerated(){
        block(aValue,index,&stop);
    }
}

//使用

let numArr = [2,4,7,8,9];
numArr.enumerateObject { (aValue, index, stop) in
    let value = aValue as! Int
    if !stop{
        print("At index \(index) value \(value)");
    }  
    if value == 7{
        print(value);
        stop = true;    
    }

}
相关问题