Timm Kent
Timm Kent

Reputation: 1268

A good way to do optional chaining

I currently do this in my code to cope with optionals...

I do a

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

        }

    }

}

Actually I would also need an "else"-clause for each and every "if let" statement. That seems totally terrible code to me! Is there no better way to do this?

Upvotes: 2

Views: 225

Answers (1)

Sebastian
Sebastian

Reputation: 8164

Yes, with switch-case and pattern matching you can achieve this:

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
}

Have a look at this blog post: Swift: Unwrapping Multiple Optionals

Edit (slightly off-topic and opinion-based): this is one of my favorite features in Swift. It also lets you implement FSMs with only few code, which is great.

Upvotes: 2

Related Questions