Last active
February 11, 2016 04:37
-
-
Save Ben-G/0ba507bc91f15828d7c7 to your computer and use it in GitHub Desktop.
Generic Function That Unwraps Optional of Arbitrary Depth
This file contains 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
// Benjamin Encz | |
// Note: Proof of Concept, you should definitely not use this! | |
import Cocoa | |
public protocol OptionalType { | |
init() | |
func unwrap() -> Any | |
} | |
extension Optional: OptionalType { | |
public func unwrap() -> Any { | |
return self! | |
} | |
} | |
func unwrapAll<T>(s: Any) -> T { | |
var returnVal: Any = s | |
while returnVal is OptionalType { | |
returnVal = (returnVal as! OptionalType).unwrap() | |
} | |
return returnVal as! T | |
} | |
let str: String?????????? = "a" | |
let unwrappedType: String = unwrapAll(str) | |
print(str) | |
// Output: | |
// Optional(Optional(Optional(Optional(Optional(Optional(Optional(Optional(Optional(Optional("a")))))))))) | |
print(unwrappedType) | |
// Output: | |
// a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment