Skip to content

Instantly share code, notes, and snippets.

@rahearn
Created September 19, 2016 18:43
Show Gist options
  • Save rahearn/3cce76e7d7e35160090042619956d8a8 to your computer and use it in GitHub Desktop.
Save rahearn/3cce76e7d7e35160090042619956d8a8 to your computer and use it in GitHub Desktop.
Custom pipe operator to conditionally call a method if optional is present
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