做可选链接的好方法

时间:2015-01-20 13:31:56

标签: swift optional

我目前在我的代码中执行此操作来处理选项......

我做了

fetchedResultController.performFetch(nil)

let results = fetchedResultController.fetchedObjects as [doesnotmatter]

// add all items to server that have no uid
for result in results {

    let uid = result.valueForKey("uid") as String?
    if uid == nil
    {
        let name = result.valueForKey("name") as String?

        let trainingday = result.valueForKey("trainingdayRel") as Trainingdays?
        if let trainingday = trainingday
        {
            let trainingUID  = trainingday.valueForKey("uid") as String?
            if let trainingUID = trainingUID
            {

                let urlstring = "http://XXXX/myGym/addTrainingday.php?apikey=XXXXXX&date=\(date)&appid=47334&exerciseUID=\(exerciseUID)"
                let sUrl = urlstring.stringByAddingPercentEscapesUsingEncoding(NSASCIIStringEncoding)
                let url = NSURL(string: sUrl!)

                // save the received uid in our database
                if let dictionary = Dictionary<String, AnyObject>.loadJSONFromWeb(url!)
                {
                    trainingday.setValue(uid, forKey: "uid")
                }
                self.managedObjectContext!.save(nil)
            }

        }

    }

}

实际上我还需要一个“else”-clause用于每一个“if let”语句。这对我来说似乎是完全可怕的代码!有没有更好的方法来做到这一点?

1 个答案:

答案 0 :(得分:2)

是的,使用switch-case和模式匹配,您可以实现此目的:

var x : SomeOptional?
var y : SomeOptional?

switch (x, y)
{
    case (.Some(let x), .Some(let y)): doSomething() // x and y present
    case (.None(let x), .Some(let y)): doSomethingElse() // x not present, but y
    // And so on for the other combinations
    default: break
}

查看此博文:Swift: Unwrapping Multiple Optionals

编辑(稍微偏离主题和基于意见):这是我在Swift中最喜欢的功能之一。它还允许您使用很少的代码实现FSM,这很棒。

相关问题