Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A port of Kotlin's scope functions to Swift.
protocol ScopeFunc {}
extension ScopeFunc {
@inline(__always) func apply(block: (Self) -> ()) -> Self {
block(self)
return self
}
@inline(__always) func letIt<R>(block: (Self) -> R) -> R {
return block(self)
}
}
extension NSObject: ScopeFunc {}
let imageView = UIImageView().apply {
$0.contentMode = .ScaleAspectFit
$0.opaque = true
$0.frame = CGRectMake(...)
$0.setImageWithURL(NSURL(string: "..."))
}
CAKeyframeAnimation(keyPath: "transform.rotation").apply {
$0.beginTime = CACurrentMediaTime()+delay
$0.duration = 0.2
$0.repeatCount = 10
$0.values = [ 0.005*M_PI, -0.005*M_PI, 0.005*M_PI ]
imageView.layer.addAnimation($0, forKey: "wiggle")
}
@guhungry

This comment has been minimized.

Copy link

commented Oct 6, 2018

you could define let using `let`

@inline(__always) func `let`<R>(block: (Self) -> R) -> R {
        return block(self)
}
@josselinPello

This comment has been minimized.

Copy link

commented Jun 20, 2019

Nice extensions!! I love apply in Kotlin and wanted to use it in Swift as well!

But there seem to be an issue with Autocomplete in the closure (I'm using XCode 10.2.1)

It only shows the useless _ self property:

image

The funny thing is that once the property and its assignment are fully typed, Xcode highlights them, meaning it recognizes them as valid:

image

Does anyone have a fix to make autocomplete work in this case?

@langleyd

This comment has been minimized.

Copy link

commented Jul 8, 2019

Kotlin scope functions also play nicely with optionals, you can also add the scope function for Optionals in swift like:

extension Optional where Wrapped: ScopeFunc {
    @inline(__always) func `let`<R>(block: (Wrapped) -> R) -> R? {
        guard let self = self else { return nil }
        return block(self)
    }
}

extension String: ScopeFunc {}

Which means you can do:

        let optionalNumberString: String? = "5"
        let optionalNumber: Int? = optionalNumberString?.let{ Int($0) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.