Optional values are fundamental to the Swift language. Because it forces developers to deal with edge cases properly. The language features of optional values enable developers to find and deal with an entire class of bugs during development. Because Swift compensates for it syntactically with features like optional chain, pattern matching, if let, or guard let. However, in some cases, optional values tend to create multi-branching conditions. Sometimes, a very succinct approach usually allows you to express a concept in one line of code rather than in a multi-line combination of if let statements.
example
Func defaultValue() -> Int {return 1111} let optional: Int? = nil print("[line \(#line)]", optional.or(else: defaultValue())) //1111 print("[line \(#line)]", optional.or(else: {// After complex calculations, Select * from user where id < 1000 if let aUser = user, User.id < 1000 {auser.upgradeTopremium ()} // Use 'filter' user.filter({$0.id < 1000})? .upgradeToPremium()Copy the code
extension
Public extension Optional {/// return true when the Optional value is null var isNone: Bool {switch self {case.some (_): Return false case. none: return true}} /// Returns the optional value or the value returned by the 'else' expression /// for example. Optional. Or (else: Selector) func or(else: Selector) @autoclosure () -> Wrapped) -> Wrapped { return self ?? ` else ` ()} / / / return the optional value or ` else ` closure return value / / for example. Optional. The or (else: {/ / /... do a lot of stuff /// }) func or(else: () -> Wrapped) -> Wrapped { return self ?? Func filter(_ predicate: (Wrapped) -> Bool) -> Wrapped? Func filter(_ predicate: (Wrapped) -> Bool) -> Wrapped? { guard let unwrapped = self, predicate(unwrapped) else { return nil } return unwrapped } }Copy the code