Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to loop through elements of array of <UnsafeMutablePointer> in Swift

Tags:

arrays

swift

I am new to Swift and wanted to loop through an array of MKMapPoints<UnsafeMutablePointer> which I get from an MKPolygon by calling myPoly.points(). However, I am stuck as to how to loop through every element of the C-Array of pointers.

for element in myPointsArray {} 

does not work and I don't know how to determine the number of elements of this kind of array in Swift. Any ideas? Thanks for your help!

like image 877
user1612877 Avatar asked Dec 14 '14 22:12

user1612877


2 Answers

UnsafeBufferPointer presents an unsafe pointer and a count as a collection so you can for..in over it, subscript it safely, pass it to algorithms that work on collections etc:

for point in UnsafeBufferPointer(start: poly.points(), count: poly.pointCount) {
    println("\(point.x),\(point.y)")
}
like image 80
Airspeed Velocity Avatar answered Nov 12 '22 06:11

Airspeed Velocity


You can get the count of points from MKPolygon.pointCount property. And iterate points with traditional for ; ; {} loop:

let myPointsArray = myPoly.points()

for var i = 0, len = myPoly.pointCount; i < len; i++ {
    let point = myPointsArray[i]
    println(point)
}
like image 40
rintaro Avatar answered Nov 12 '22 06:11

rintaro