if and guard

The example below shows how you use an if statement with a case condition:

func process(point: (x: Int, y: Int, z: Int)) -> String { if case (0, 0, 0) = point {

return "At origin"

}

return "Not at origin"

}

let point = (x: 0, y: 0, z: 0)

let response = process(point: point) // At origin

You could write the implementation of the function to use a guard statement and achieve the same effect:

func process(point: (x: Int, y: Int, z: Int)) -> String { guard case (0, 0, 0) = point else {

return "Not at origin"

}

// guaranteed point is at the origin return "At origin"

}

In a case condition, you write the pattern first followed by an equals sign, =, and then the value you want to match to the pattern. if statements and guard statements work best if there is a single pattern you care to match.

results matching ""

    No results matching ""