Skip to content

Instantly share code, notes, and snippets.

@christianselig
Last active November 4, 2024 07:15
Show Gist options
  • Select an option

  • Save christianselig/6ccb9b1538012aa0438689481e5fa960 to your computer and use it in GitHub Desktop.

Select an option

Save christianselig/6ccb9b1538012aa0438689481e5fa960 to your computer and use it in GitHub Desktop.

Revisions

  1. christianselig revised this gist Apr 14, 2023. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions Optional+UseIfNotNil.swift
    Original file line number Diff line number Diff line change
    @@ -1,11 +1,11 @@
    // Before πŸ˜•
    let firstSubviewWidth1: CGFloat? = {
    let doingSomethingToOptionalView1: CGFloat? = {
    guard let firstSubview = subviews.first else { return nil }
    return firstSubview.bounds.width
    return (firstSubview.bounds.width / 2.0) + otherView.bounds.width
    }()

    // After 😊
    let firstSubviewWidth2 = subviews.first.useIfNotNil { $0.bounds.width }
    let doingSomethingToOptionalView2 = subviews.first.useIfNotNil { ($0.bounds.width / 2.0) + otherView.bounds.width }


    // βš™οΈ Internals
  2. christianselig created this gist Apr 14, 2023.
    22 changes: 22 additions & 0 deletions Optional+UseIfNotNil.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    // Before πŸ˜•
    let firstSubviewWidth1: CGFloat? = {
    guard let firstSubview = subviews.first else { return nil }
    return firstSubview.bounds.width
    }()

    // After 😊
    let firstSubviewWidth2 = subviews.first.useIfNotNil { $0.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
    }
    }
    }