Forked from terhechte/pattern-examples.swift
Last active
September 6, 2015 13:02
Revisions
-
saiday revised this gist
Sep 6, 2015 . 1 changed file with 2 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -54,7 +54,7 @@ print(valueTupleType((5, u))) print(valueTupleType((5, b))) // 6. Enumeration Pattern enum Test { case T1(Int, Int) case T2(Int, Int) @@ -75,6 +75,7 @@ func enumeration(a: Test) -> Bool { enumeration(.T1(1, 2)) enumeration(.T2(1, 2)) // 7. Expression Pattern struct Soldier { let hp: Int } -
terhechte renamed this gist
Aug 22, 2015 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
terhechte created this gist
Aug 22, 2015 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,100 @@ 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))