Reputation: 93
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?
Upvotes: 6
Views: 12831
Reputation: 12353
Tested in Swift 2.1, Xcode 7. works !
var myItems : String?
myItems = ItemsTextfield.text
myItems as! AnyObject
Upvotes: 1
Reputation: 6325
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!"
Upvotes: 2
Reputation: 71854
You need to make your selectedNumber
to optional like this:
struct numb {
static var selectedNumber: String?
}
Upvotes: 1