Extension methods for generics

In kotlin

we can extend functionality of a general type apply

, for example:

inline fun <T> T.apply(block: T.() -> Unit): T

      

Thus, we can use this function to precisely set the properties of such objects:

titleView.apply {
    setTextSize(10)
    setTextColor(RED)
}

      

Or even keep common styles as constants:

T.() -> Unit

means an extension function for a type T

that returns Unit ( void

, nothing)

val TITLE_STYLE: TextView.() -> Unit = {
    setTextSize(10)
    setTextColor(RED)
}
//...
titleView.apply(TITLE_STYLE)

      

Is something like this possible in a fast? My best attempt looks like this:

func apply<T: UIView>(_ param: T, _ style: (T) -> ()) {
    style(param)
}

      

We can use it like this:

let titleLabel: UILabel = ...
apply(titleLabel) { label in
    label.font = UIFont(name: "SFUIText-Regular", size: 14)
    label.textColor = UIColor.red
}

      

Or using constants:

let accentTitle: (UILabel) -> () = { label in
    label.font = UIFont(name: "SFUIText-Regular", size: 12)
    label.textColor = UIColor.red
}
//...
apply(titleLabel, accentTitle)

      

Can I write apply

as an extension function in swift? This is ugly and can fail at runtime:

extension NSObject {

    func apply<T>(_ style: (T) -> ()) {
        guard let obj = self as? T else {
            preconditionFailure("Object \(self) does not confirms to type: \(T.self)")
        }
        style(obj)
    }
}

titleLabel.apply() { (label: UILabel) in
    label.font = UIFont(name: "SFUIText-Regular", size: 14)
    label.textColor = UIColor.red
}

titleLabel.apply(accentTitle)

      

+3
swift


source to share


No one has answered this question yet

Check out similar questions:

409
How to generate a random number in Apple Swift language?
360
Does it quickly have a method to trim to String?
337
How do I define additional methods in the Swift protocol?
109
Overriding Methods in Swift Extensions
eleven
How do I display OptionSet values ​​in a readable form?
five
Wrapping a generic method in a class extension
4
Adding a custom UIViewcontroller for a routine programmatically, but getting the error "Unable to convert value to type ..."
1
Swift ambiguous type in a fluent generic extension function
0
How to distinguish all labels from iPads and phones without adding Regular, Regular for each one?



All Articles
Loading...
X
Show
Funny
Dev
Pics