Skip to content

Instantly share code, notes, and snippets.

@saiday
Forked from terhechte/pattern-examples.swift
Last active September 6, 2015 13:02
Show Gist options
  • Save saiday/09c7968c6bcbcfd57bd2 to your computer and use it in GitHub Desktop.
Save saiday/09c7968c6bcbcfd57bd2 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)))
// 6. 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))
// 7. Expression Pattern
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