Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

componentsSeparatedByString returns a AnyObject, not a String

Tags:

swift

As it's written in the Quick Help from Xcode

func componentsSeparatedByString(separator: String!) -> AnyObject[]!

So, componentsSeparatedByString returns a AnyObject type.

After this part of code

 let bundle = NSBundle.mainBundle()
    let path = bundle.pathForResource("data", ofType: "txt")
                              /*data.txt is like that :
                     "Cat"
                     "Dog"
                     "Mouse"
*/
    let dico = NSString(contentsOfFile: path).componentsSeparatedByString("\n")

Xcode doesn't want me to compare, for instance, dico[3] to myString.

if  myString == dico[3] { //Error : Type 'AnyObject' cannot be implicitly downcast to 'NSString'
       return true
}

However, println("\(dico[1])") displays a String.

What can I do to be able to have an array full of Strings (and not AnyObject values), thus I'm able to compare myString to dico[3]?

like image 771
Piercy Avatar asked Jan 19 '26 17:01

Piercy


1 Answers

You can cast the array like this:

let dico = NSString(contentsOfFile: path).componentsSeparatedByString("\n") as [String]
like image 132
Jack Avatar answered Jan 22 '26 12:01

Jack



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!