Last active
November 4, 2024 07:15
-
-
Save christianselig/6ccb9b1538012aa0438689481e5fa960 to your computer and use it in GitHub Desktop.
This file contains 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
// Before 😕 | |
let doingSomethingToOptionalView1: CGFloat? = { | |
guard let firstSubview = subviews.first else { return nil } | |
return (firstSubview.bounds.width / 2.0) + otherView.bounds.width | |
}() | |
// After 😊 | |
let doingSomethingToOptionalView2 = subviews.first.useIfNotNil { ($0.bounds.width / 2.0) + otherView.bounds.width } | |
// ⚙️ Internals | |
extension Optional { | |
/// If the value is not nil, transform it in the specified block. If it is nil, simply returns nil back. Functionally identical to the `map` function on `Optional`, but better named. | |
func useIfNotNil<U>(_ transform: (Wrapped) throws -> U) rethrows -> U? { | |
switch self { | |
case .some(let value): | |
return .some(try transform(value)) | |
case .none: | |
return .none | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment