Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active February 11, 2016 11:01
Show Gist options
  • Save KentarouKanno/0e151abe6ae011e013db to your computer and use it in GitHub Desktop.
Save KentarouKanno/0e151abe6ae011e013db to your computer and use it in GitHub Desktop.
guard

guard

★ 条件によって処理を切り分ける

let array = [1, 2, 3]

guard !array.isEmpty else {
    return
}

// 以下配列が空でない場合の処理

★ Optional型をUnwrapする

var optionalValue: Int? = 5

guard let value = optionalValue else { 

    // 以下のいずれかでスコープを抜ける
    return
    break
    continue
    throw
}

let result = value + 3

// ------------------

guard var value = optionalValue else { 
    return
}

value += 3

// ------------------

var optionalValue: Int? = 5

// Unwrap & 条件付き
guard let value = optionalValue where value > 3 else {
    return
}

let result = value + 3

// ------------------

let optionalValue1: Int? = 5
let optionalValue2: Int? = 7

// 複数Unwrap & 複数条件付き
guard let value1 = optionalValue1, value2 = optionalValue2 where value1 > 3 && value2 > 5 && value2 > value1 else {
    return
}

let result = value1 + value2
//=> 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment