Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enumerate function in Swift

Tags:

swift

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'

like image 454
Jacob Rohde Avatar asked Feb 23 '26 13:02

Jacob Rohde


2 Answers

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.

like image 123
Mick MacCallum Avatar answered Feb 26 '26 09:02

Mick MacCallum


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
...
like image 39
Craig Otis Avatar answered Feb 26 '26 07:02

Craig Otis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!