I am trying to iterate over an array of strings, using the global enumerate function in Swift.
It looks like this:
let fontNames = UIFont.fontNamesForFamilyName(familyName)
for (index, value) in enumerate(fontNames) {
// Do something here
}
But Xcode complains with an error saying
Cannot convert the expression's type 'EnumerateGenerator' to type '$T1'
fontNamesForFamilyName() returns AnyObject[]!, which can't be directly enumerated. You have explicitly type your fontNames array.
let fontNames: Array = UIFont.fontNamesForFamilyName(familyName)
for (index, value : AnyObject) in enumerate(fontNames) {
println(value)
}
And as @Van Du Tran pointed out in the comments below, the syntax for enumerate has changed in Swift 2. Now you can use the following.
let fontNames: Array = UIFont.fontNamesForFamilyName(familyName)
for (index, value) in fontNames.enumerate() {
print(value)
}
It's also worth noting that since fontNamesForFamilyName now uses an Objective C generic type, it returns [String] so no conversion from AnyObject is needed.
I might disagree with @0x7fffffff's answer. I think the issue is not that AnyObject[] can't be directly enumerated, but rather that it's returned as an implicitly unwrapped optional.
As a test:
let myStuff: AnyObject[] = ["Neat"]
for (index, value) in enumerate(myStuff) { // < No issues
print("\(value)")
}
let myStuff2: AnyObject[]! = ["Neat"]
for (index, value) in enumerate(myStuff2) { // < Compiler error
print("\(value)")
}
I think a better solution is to unwrap the optional in your enumerate() function:
for (index, value) in enumerate(fontNames!) { // < Note the bang
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With