Skip to content

Instantly share code, notes, and snippets.

@christianselig
Last active November 4, 2024 07:15
Show Gist options
  • Save christianselig/6ccb9b1538012aa0438689481e5fa960 to your computer and use it in GitHub Desktop.
Save christianselig/6ccb9b1538012aa0438689481e5fa960 to your computer and use it in GitHub Desktop.
// 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