vanniktech
04/16/2020, 4:37 PMapply
method on iOS that’s behaving similar to Kotlin’s apply?Sam
04/16/2020, 5:33 PMvanniktech
04/16/2020, 5:52 PMSam
04/16/2020, 7:12 PMAny
or AnyObject
. You can do something like this:
protocol Applier {
associatedtype Applying
func apply(_ fn: (Applying) -> Void) -> Applying
}
extension Applier {
func apply(_ fn: (Applying) -> Void) -> Applying{
fn(self as! Self.Applying)
return self as! Self.Applying
}
}
class Foo {
var bar = "baz"
}
extension Foo: Applier {
typealias Applying = Foo
}
let foo = Foo().apply { `self` in
self.bar = "baz2"
}
print(foo.bar)
class Foo2: Foo {
var baz = "foo"
}
let foo2 = Foo2().apply { `self` in
self.bar = "baz2"
//self.baz = "Does not work. Self is of type Foo"
}
It isn’t very useful though as you have to declare the conformance of the type to the Applier
protocol for each class you want to use it on. The other caveat is the subclass issue. If you make UIView
conform to the protocol and try to use it on a subclass such as UILabel
, the type of the argument passed into your apply function is UIView
which is only minimally useful. Also there should be a way to do the above without the force casts. I’m just too tired to parse through all of the protocol associated type nuances right now.let
for Swift. It can only be used on optionals which is about 99% of when I use a let
function anyway.
extension Optional {
/// Function similar to Kotlin let that executes a block of code on an optional if the optional has a value.
///
/// - Parameter execute: The block to be executed.
func `let`(_ execute: (Wrapped) -> Void) {
if let wrapped = self {
execute(wrapped)
}
}
}
vanniktech
04/16/2020, 7:20 PMapply
looks really distasteful. That let
function should come handy though, thanksSam
04/16/2020, 8:08 PMNSObject
will make it apply to every object in UIKit
and any other Swift object that has the @objc
attribute.vanniktech
04/17/2020, 7:29 AM