if let ...

36 views
Skip to first unread message

Marco S Hyman

unread,
Jul 14, 2015, 3:49:54 PM7/14/15
to swift-l...@googlegroups.com
Both of the following code bits seem to do the same thing...

if let foo = optionalFoo,
let bar = optionalBar {
// ...
}

if let foo = optionalFoo,
bar = optionalBar {
// ...
}

Is there any reason why one should be preferred over the other?

Chris Lattner

unread,
Jul 15, 2015, 1:03:42 AM7/15/15
to Marco S Hyman, swift-l...@googlegroups.com
You *must* use the former if you want to use a boolean condition between them with a "where" clause. In the absence of a where clause, this is a style question.

IMHO, I'd use the former when wrapping the lines as you have, but use the later when both foo/bar are on the same line, e.g.:

if let foo = optionalFoo, bar = optionalBar {
// ...
}

-Chris

Bruno Berisso

unread,
Jul 29, 2015, 10:38:33 AM7/29/15
to Chris Lattner, Marco S Hyman, swift-l...@googlegroups.com
I try it in a playground and can't find a difference. This is the code:


let op1: Any? = "test"
let op2: Any? = 4

//Version 1
//
if let a = op1 as? String, 
        b = op2 as? Int 
   where a == "test" && b > 1 {
    "work"
} else {
    "don't work"
}

//Version 2
//
if let a = op1 as? String, 
   let b = op2 as? Int 
   where a == "test" && b > 1 {
    "work"
} else {
    "don't work"
}


This always "work"


--
You received this message because you are subscribed to the Google Groups "Swift Language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to swift-languag...@googlegroups.com.
To post to this group, send email to swift-l...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/swift-language/BA41571C-0EC3-4287-BB25-4950520A3438%40apple.com.
For more options, visit https://groups.google.com/d/optout.

Jim Dovey

unread,
Jul 29, 2015, 12:35:18 PM7/29/15
to Bruno Berisso, Chris Lattner, Marco S Hyman, swift-l...@googlegroups.com
The difference is when you place a `where` clause *between* the assignments, i.e. before assigning `b`:

// This is valid
if let a = op1 as? String where !a.isEmpty,
let b = op2 as? String {
// work
}

// This is not
if let a = op1 as? String where !a.isEmpty,
b = op2 as? String { // ← missing `let`
// work
}

Cheers,
-Jim

Marco S Hyman

unread,
Jul 29, 2015, 3:12:42 PM7/29/15
to Bruno Berisso, swift-l...@googlegroups.com
let op1: Any? = "test"
let op2: Any? = 1

if let a = op1 as? String where a == "test",
let b = op2 as? Int where b > 1 {
"work"
} else {
"don't work”
}

That will work because all conditions are true. Change op1 from “test” to
something else and “don’t work” is the result. Change opt2 from 4 to 1 and
“don’t work” is the result, etc.

Tested with Xcode 7 beta 4
Reply all
Reply to author
Forward
0 new messages