对于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"]
{
...
答案 0 :(得分:2)
展开数组的内容或使用nil coalescing运算符:
if let str = arr[0] as? String {
let title = "Preset \(str)"
}
或
"Preset \(arr[0]) ?? \(someDefaultValue)"
如果s
是String?
,您想首先打开它:
if let s = info["description"] as? String {
// ...
}