获取字符串显示的可选项

时间:2016-07-20 13:12:37

标签: ios swift string

对于Apple Watch扩展程序,我提出了一个AlertController,我得到的显示方式如“Preset Optional(2)”而不是“Preset 2” - 下面是我的代码。我如何摆脱Optional(不认为Strings有他们)

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])
}

以下是info [“description”]的派生方式:

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

1 个答案:

答案 0 :(得分:2)

展开数组的内容或使用nil coalescing运算符:

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

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

如果sString?,您想首先打开它:

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