Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert String to AnyObject in swift

Tags:

casting

swift

I have a static string variable

struct numb {

    static var selectedNumber: String = String()

}

I am trying to unwrap ( while casting it as AnyObject) the value and assign it to messageComposeViewController

 if let textMessageRecipients :AnyObject  =  numb.selectedNumber 
    {
     messageComposeVC.recipients = textMessageRecipients as? [AnyObject]
    messageComposeVC.body = "Testing 123!"
    }

the compiler is throwing an error

bound value in a conditional binding must be of Optional type

How do I convert my string to AnyObject and assign it to the message view controller?

like image 693
Adeel Avatar asked Sep 27 '22 14:09

Adeel


2 Answers

From your examples and the error you see, you are attempting to unwrap a value that isn't optional. You don't need to use if let when there is a value. You can force a cast using if let like this:

if let myValue:AnyObject = numb.selectedNumber as? AnyObject

This will produce a warning saying that casting a String to AnyObject will always succeed, again you don't need the if let, your casts will always succeed.

Your final example should look something like:

messageComposeVC.recipients = [numb.selectedNumber] as [AnyObject]
messageComposeVC.body = "Testing 123!"
like image 147
utahwithak Avatar answered Oct 12 '22 17:10

utahwithak


You need to make your selectedNumber to optional like this:

struct numb {

    static var selectedNumber: String?

}
like image 21
Dharmesh Kheni Avatar answered Oct 12 '22 16:10

Dharmesh Kheni