简体   繁体   中英

ObjC to Swift array loop , need help please

I have the following loop in ObjC: myArray is a 2D array.

for (NSArray *newArray in myArray) {

    for (int i = 0; i < newArray.count; i++) {

        NSArray *points = [newArray[i] componentsSeparatedByString:@","];
  }
}...

I am trying to do the same thing using Swift but am struggling to find a way to get componentsSeperatedByString:

for newArray in myArray {

        for i in 0..<newArray.count {
            var pnts:NSArray = newArray[i].componentsSeparatedByString(",")
        }
    }

The first step is to convert your NSArray to have the proper type, in this case it looks like you want:

if let array = myArray as? [[String]] {
}

Then you have a number of options, the most effective of which is probably a nested iteration:

let myArray = NSArray(arrayLiteral:
    NSArray(arrayLiteral: "150.10,310.20"),
    NSArray(arrayLiteral: "400.10,310.20", "100,200")
)

if let source = myArray as? [[String]] {
    for array in source {
        for element in array {
            print(element.componentsSeparatedByString(","))
        }
    }
}
// -> ["150.10", "310.20"]
//    ["400.10", "310.20"]
//    ["100", "200"]

If all you're wanting to do is extract the points, you can use map:

if let source = myArray as? [[String]] {
    print(source.map {
        $0.map { $0.componentsSeparatedByString(",") }
        }
    )
}    
// -> [[["150.10", "310.20"]], [["400.10", "310.20"], ["100", "200"]]]

If you want to collapse the points into a single array, you can use flatMap, as pointed out by Helium, which will turn the array of arrays, into a simple array:

if let source = myArray as? [[String]] {
    print(source.flatMap {
        $0.map { $0.componentsSeparatedByString(",") }
        }
    )
}
// -> [["150.10", "310.20"], ["400.10", "310.20"], ["100", "200"]]

Of course, you can also extract it as [[Double]] instead of [[String]] by using yet another map call:

if let source = myArray as? [[String]] {
    print(source.map {
        $0.map { $0.componentsSeparatedByString(",").map { Double($0)! } }
    })
}
// -> [[150.1, 310.2], [400.1, 310.2], [100.0, 200.0]]

If you want the pnts, you can use flatmap, which will flatten the 2D array into a single array with the points.

let pnts = myArray.flatMap { array in
            array.map { object in
            object.componentsSeparatedByString(",") 
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM