简体   繁体   中英

How to cast tuples in a “for in” enumeration in swift?

My enumeration is as follows:

for (i, poi) in enumerate(self.pois) {
//
}

I'd like to cast i and poi as (int, NSDictionary)

I tried many things, including:

for (i, poi) in enumerate(self.pois) as [(int, NSDictionary)]

Any idea?

this little package may be helpful for you:

let justAnArray: Array<(i: Int, poi: NSDictionary)> = Array()

// fill the array...

for temporaryTuple: (i: Int, poi: NSDictionary) in justAnArray {

    // enumerate through elements...

    println(temporaryTuple.i)
    println(temporaryTuple.poi)
}

or

with typealias :

typealias CustomTuple = (i: Int, poi: NSDictionary)

var justAnArray: Array<CustomTuple> = Array()

// fill the array ...

for temporaryTuple: CustomTuple in justAnArray {

    // enumerate through elements...

    println(temporaryTuple.i)
    println(temporaryTuple.poi)
}

What is the current type of poi ? If poi is a Dictionary then the cast is simple.

for (i, poi) in enumerate(self.pois.map { $0 as NSDictionary }) {
    println("\(i) : \(poi)")
}

Or you can do make the cast as the first line of the for loop.

for (i, poiDictionary) in enumerate(self.pois) {
    let poi = poiDictionary as NSDictionary
    println("\(i) : \(poi)")
}

If poi is an object, then you will need to call a method on poi to get the NSDictionary .

for (i, poi) in enumerate(self.pois.map { $0.toNSDictionary() }) {
    println("\(i) : \(poi)")
}

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