Reputation:
Having the following for in loop:
for entry in entries {
println("entry: \(entry)")
}
I want to cast the entry in the loop header to String. I cannot do the following because it is no Array:
for entry in entries as! [String] {
}
because entries is not an array.
Edit: entries conforms the SequenceType
protocol.
How can I cast entry in the loop header to String?
Upvotes: 1
Views: 129
Reputation: 539915
The "easy" solution would be
for x in entries {
if let y = x as? String {
println(y)
}
}
but that is probably not what you are looking for.
If it is acceptable that an array of all elements is created first then the following would work as well:
let a = Array(entries)
for x in a as! [String] {
println(x)
}
If entries
is a sequence producing AnyObject
elements, and you
know that all these elements are in fact strings, then you can
create a new sequence producing String
s with
let stringSeq = SequenceOf { () -> GeneratorOf<String> in
var gen = entries.generate()
return GeneratorOf {
return gen.next() as? String
}
}
for x in stringSeq {
println(x) // x is a `String`
}
What you probably should do is to change the definition of the
entries
generator itself so that it produces strings in the first place. Example (based on the code in your previous
question Make Class iterable with a for in Loop? and this blog post):
// Class containing an array of `AnyObject`:
class MyArrayClass {
var array: [AnyObject] = ["a", "b", "c"]
}
// Sequence producing `String`:
extension MyArrayClass : SequenceType {
func generate() -> GeneratorOf<String> {
var index = 0
return GeneratorOf {
if index < self.array.count {
return self.array[index++] as? String
} else {
return nil
}
}
}
}
// Now the enumeration gives strings:
let entries = MyArrayClass()
for x in entries {
println(x)
}
Upvotes: 1
Reputation: 6726
There's map for that ;-)
let entries = NSSet(array: ["Foo", "Bar"])
for entry in map(entries, {$0 as! String}) {
println("entry: \(entry)")
}
Hope it helps
Upvotes: 2