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
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)
}
}
ie unwrap the enumerator with an optional binding before using it in the loop.
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.