hakonbogen hakonbogen - 1 year ago 65
Swift Question

How to use if let with another statement in swift?

If want to both assign a string and check that its not empty in Swift.

if let alternative3Text = attributes.stringForKey("choiceThree") && alternative3Text != "" {
// do stuff with alternative3Text

Is this possible in Swift, or do i have to do a nested if-statement?

Answer Source

Update: As of Swift 3 (Xcode 8), additional clauses are separated by a comma, not by where:

if let alternative3Text = attributes.string(forKey: "choiceThree"),
        alternative3Text != "" {
    // do stuff with alternative3Text

Update: As of Swift 1.2 (Xcode 6.3 beta), you can combine optional binding with additional conditions:

if let alternative3Text = attributes.stringForKey("choiceThree") where alternative3Text != "" {
   // do stuff with alternative3Text

Using switch-case still works but is not necessary anymore for this purpose.

Old answer: It is not possible with an if statement, but with switch. A switch case can use a where clause to check for additional conditions (documentation).

Assuming (from your question) that attributes.stringForKey("choiceThree") returns String?, the following would work:

switch (attributes.stringForKey("choiceThree")) {
case .Some(let alternative3Text) where alternative3Text != "":
    // alternative3Text is the unwrapped String here