Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Created February 11, 2015 04:15
Show Gist options
  • Save natecook1000/8ddad9b0bc0ef49ab4c7 to your computer and use it in GitHub Desktop.
Save natecook1000/8ddad9b0bc0ef49ab4c7 to your computer and use it in GitHub Desktop.
Some extremely contrived examples using Swift 1.2 if-let bindings
// OptionalBinding.swift
// as seen in http://nshipster.com/swift-1.2/
//
// (c) 2015 Nate Cook, licensed under the MIT license
let a: Int? = 10
let b: Int? = 5
let c: Int? = 3
let d: Int? = -2
let e: Int? = 0
// ----------------------------------------------------------
// Example 1: add a + b if both are greater than zero
// original
if let a = a {
if a > 0 {
if let b = b {
if b > 0 {
println("a + b = \(a + b)")
}
}
}
}
// swift 1.2
if let a = a where a > 0, let b = b where b > 0 {
println("a + b = \(a + b)")
}
// ----------------------------------------------------------
// Example 2: compute (a + b) / c if c does not equal zero
// original
if let a = a {
if let b = b {
if let c = c {
if c != 0 {
println("(a + b) / c = \((a + b) / c)")
}
}
}
}
// swift 1.2
if let a = a, b = b, c = c where c != 0 {
println("(a + b) / c = \((a + b) / c)")
}
// ----------------------------------------------------------
// Example 3: compute (a + b) / (c + d) if a > b and
// (c + d) does not equal zero
// original
if let a = a {
if let b = b {
if a > b {
if let c = c {
if let d = d {
if c + d != 0 {
println("(a + b) / (c + d) = \((a + b) / (c + d))")
}
}
}
}
}
}
// swift 1.2
if let a = a, b = b where a > b,
let c = c, d = d where c + d != 0
{
println("(a + b) / (c + d) = \((a + b) / (c + d))")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment