Skip to content

Instantly share code, notes, and snippets.

@Ben-G
Last active February 11, 2016 04:37
Show Gist options
  • Save Ben-G/0ba507bc91f15828d7c7 to your computer and use it in GitHub Desktop.
Save Ben-G/0ba507bc91f15828d7c7 to your computer and use it in GitHub Desktop.
Generic Function That Unwraps Optional of Arbitrary Depth
// 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