Created
July 12, 2016 18:34
-
-
Save algal/bfb25579e97a119a6888d00f993e1dcb to your computer and use it in GitHub Desktop.
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 characters
// overloading on function return values to | |
// enable destructuring a JSON-like type | |
import Foundation | |
enum JSONType { | |
case JBool(Bool) | |
case JNumber(Int) | |
case JString(String) | |
} | |
extension JSONType { | |
func value() -> Bool? { | |
guard case let .JBool(v) = self else { return nil } | |
return v | |
} | |
func value() -> Int? { | |
guard case let .JNumber(v) = self else { return nil } | |
return v | |
} | |
func value() -> String? { | |
guard case let .JString(v) = self else { return nil } | |
return v | |
} | |
} | |
let jString:JSONType = JSONType.JString("hello") | |
if let s:String = jString.value() { | |
print("found a string") | |
} | |
else { | |
print("did not find a string") | |
} | |
if let s:Int = jString.value() { | |
print("found a string") | |
} | |
else { | |
print("did not find a string") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment