Created
September 19, 2016 18:43
-
-
Save rahearn/3cce76e7d7e35160090042619956d8a8 to your computer and use it in GitHub Desktop.
Custom pipe operator to conditionally call a method if optional is present
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
infix operator |? | |
func |?<I,O>(left: I?, pipeFunc: ((I) -> O?)) -> O? { | |
guard let value = left else { return nil } | |
return pipeFunc(value) | |
} | |
let formatter = DateFormatter() | |
formatter.locale = Locale(identifier: "en_US_POSIX") | |
formatter.timeZone = NSTimeZone.local | |
formatter.dateFormat = "MM/dd/yyyy" | |
func convertToDate(_ str: String) -> Date? { | |
return formatter.date(from: str) | |
} | |
var birthday: String? = "9/14/2020" | |
let result: Date? = birthday |? { return convertToDate($0) } | |
let mapResult: Date?? = birthday.map { return convertToDate($0) } | |
let flatMapResult: Date? = birthday.flatMap { return convertToDate($0) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment