3

Just a bit silly question and answered many times, but nevertheless i can't understand

    while let element = enumdirs?.nextObject() as? String {
        println(element)
    }

The above causes error: Swift string doesn't conform to anyobject, so with as ,but

    while let element = enumdirs?.nextObject() {
        println(element as? String)
    }

works perfectly. What the problem with casting in while statement

Olexiy Pyvovarov
  • 870
  • 2
  • 17
  • 32

1 Answers1

4

AnyObject can represent an instance of any class type. A conditional cast from AnyObject to String works only because String is bridged to NSString if necessary.

However, this seems not to work with the optional chaining in

while let element = enumdirs?.nextObject() as? String { ... }

so this might be a compiler bug. It works as expected if you cast to NSString instead:

while let element : String = enumdirs?.nextObject() as? NSString { ... }

or unwrap explicitly:

while let element = enumdirs!.nextObject() as? String { ... }

But the better solution might be

if let enumdirs = NSFileManager.defaultManager().enumeratorAtPath(...) {
    while let element = enumdirs.nextObject() as? String {
        println(element)
    }
}

i.e. unwrap the enumerator with an optional binding before using it in the loop.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382