Skip to content

Instantly share code, notes, and snippets.

@erdemildiz
Last active September 26, 2020 16:15
Show Gist options
  • Save erdemildiz/e2a3f9f4ade9464dec7025e5b7ef92c9 to your computer and use it in GitHub Desktop.
Save erdemildiz/e2a3f9f4ade9464dec7025e5b7ef92c9 to your computer and use it in GitHub Desktop.
Self enclosing nice function in swift
func configure<T>(
_ value: T,
using closure: (inout T) throws -> Void
) rethrows -> T {
var value = value
try closure(&value)
return value
}
@erdemildiz
Copy link
Author

Example:

class HeaderView: UIView {
    let imageView = configure(UIImageView()) {
        $0.translatesAutoresizingMaskIntoConstraints = false
        $0.contentMode = .scaleAspectFit
        $0.image = .placeholder
    }

    let label = configure(UILabel()) {
        $0.translatesAutoresizingMaskIntoConstraints = false
        $0.numberOfLines = 2
        $0.font = .preferredFont(forTextStyle: .headline)
    }
    
    ...
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment