Skip to content

Instantly share code, notes, and snippets.

@acalism
Last active February 27, 2018 06:39
Show Gist options
  • Save acalism/7031e93289ee5049c1b694469e49d256 to your computer and use it in GitHub Desktop.
Save acalism/7031e93289ee5049c1b694469e49d256 to your computer and use it in GitHub Desktop.
Convert to chain-invocation
protocol InstantMap {
func instantMap<T>(_ transform: (Self)->T) -> T
func instantFlatMap<T>(_ transform: (Self)->T?) -> T?
}
extension InstantMap {
func instantMap<T>(_ transform: (Self)->T) -> T {
return transform(self)
}
func instantFlatMap<T>(_ transform: (Self)->T?) -> T? {
return transform(self)
}
}
extension Int: InstantMap {}
3.instantMap({ $0 + Int(arc4random_uniform(32)) })
3.instantMap({ String($0) })
extension String: InstantMap {}
if true {
let imageUrlStr: String? = "https://m.baidu.com"
if let u = imageUrlStr?.instantFlatMap({ URL.init(string: $0) }) {
print(u)
}
if let imageUrlStr = imageUrlStr, let u = URL.init(string: imageUrlStr) {
print(u)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment