Swift Optional values out of an NSSet

755 Views Asked by At

Self.vertices is an NSSet. I'm having trouble getting the Vertex value out of the optional

The code below crashes in playgrounds.

func getVertex (x: Double, y: Double,z: Double) -> Vertex?
{

    for v : Vertex! in self.vertices {

        if v.isEqualTo(x, y: y, z: z) {
            return v
        }
    }
    return nil

}
2

There are 2 best solutions below

0
holex On BEST ANSWER

that may be helpful:

let set: NSSet = // ...

for object : AnyObject in set {
    if let vertex = object as? Vertex {
        // do the main course
    }
}
0
Yong Li On

I believe self.vertices contains AnyObject. So you should use following code

func getVertex (x: Double, y: Double,z: Double) -> Vertex?
{
    for v : AnyObject in self.vertices {
       if v is Vertex {
           if v.isEqualTo(x, y: y, z: z) {
              return v
           }
       }
    }
    return nil
}