Radagast the Brown Radagast the Brown - 4 months ago 19
Swift Question

Getting Optional for String display

For an Apple Watch extension I am presenting an AlertController and I am getting a display like "Preset Optional(2)" instead of "Preset 2" - below is my code. How do I get rid of the Optional (didn't think Strings had them)

if let s = info["description"]
{
let action = WKAlertAction(title: "OK", style: WKAlertActionStyle.Default, handler: { () -> Void in
//
})

//let arr = s.componentsSeparatedByString("_")
let arr = s.characters.split("_", maxSplit: Int.max, allowEmptySlices: false).map(String.init)
self.presentAlertControllerWithTitle("Preset \(arr[0])", message: "\n\(arr[1])", preferredStyle: WKAlertControllerStyle.Alert, actions: [action])
}


Here is how info["description"] is derived:

func session(session: WCSession, didReceiveMessage message: [String : AnyObject])
{
if let info = message as? Dictionary<String,String>{
if let s = info["description"]
{
...

JAL JAL
Answer

Unwrap the contents of the array or use the nil coalescing operator:

if let str = arr[0] as? String {
    let title = "Preset \(str)"
}

or

"Preset \(arr[0]) ?? \(someDefaultValue)"

If s is a String? you want to unwrap that first:

if let s = info["description"] as? String {
    // ...
}
Comments