Skip to content

Instantly share code, notes, and snippets.

@chrishamant
Forked from terhechte/pattern-examples.swift
Created October 27, 2015 19:15
Show Gist options
  • Save chrishamant/159e9326955a0f4eb076 to your computer and use it in GitHub Desktop.
Save chrishamant/159e9326955a0f4eb076 to your computer and use it in GitHub Desktop.
Swift pattern examples for the swift, for, and guard keywords
import Foundation
// 1. Wildcard Pattern
func wildcard(a: String?) -> Bool {
guard case _? = a else { return false }
for case _? in [a] {
return true
}
switch a {
case _?: return true
case nil: return false
}
}
wildcard("yes")
wildcard(nil)
// 2. Identifier Pattern
func identifier(a: Int) -> Bool {
guard case 5 = a else { return false }
for case 5 in [a] {
return true
}
switch a {
case 5: return true
default: return false
}
}
identifier(5)
// 3. Value Binding Pattern
// 4. Tuple Pattern
// 5. Type Casting Pattern
func valueTupleType(a: (Int, Any)) -> Bool {
guard case let (x, _ as String) = a else { return false}
print(x)
for case let (a, _ as String) in [a] {
print(a)
return true
}
switch a {
case let (a, _ as String):
print(a)
return true
default: return false
}
}
let u: Any = "a"
let b: Any = 5
print(valueTupleType((5, u)))
print(valueTupleType((5, b)))
// Enumeration Pattern
enum Test {
case T1(Int, Int)
case T2(Int, Int)
}
func enumeration(a: Test) -> Bool {
guard case .T1(_, _) = a else { return false }
for case .T1(_, _) in [Test.T1(1, 2)] {
return true
}
switch a {
case .T1(_, _): return true
default: return false
}
}
enumeration(.T1(1, 2))
enumeration(.T2(1, 2))
struct Soldier {
let hp: Int
}
func ~= (pattern: Soldier, value: Soldier) -> Bool {
return pattern.hp == value.hp
}
func expression(a: Soldier) -> Bool {
guard case Soldier(hp: 10) = a else { return false }
for case Soldier(hp: 10) in [a] {
return true
}
switch a {
case Soldier(hp: 10): return true
default: return false
}
}
expression(Soldier(hp: 10))
expression(Soldier(hp: 11))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment