I've been porting code back and forth between Swift and Kotlin. Inspired by this answer, I've been using ?.let { } ?: run {}
as replacements for the many places I use if let ... { } else {}
in Swift.
I've really come to like the Kotlin expression though. In my opinion it's more general than the keyword specific if let
concoction. So for parity's sake--or at least for the sake of learning by trying silly experiments--I thought I'd try to implement the let
construct in Swift.
Because let
is a keyword in Swift, I discovered right away that I'd need to put backticks, or use a different name, like cull
. That led to this uncompilable code:
extension Any {
func cull<R>(block:(Self) -> R) -> R {
return block(self)
}
}
which given my apprentice level skills, probably has numerous problems. But most importantly, I'm informed that I can't extend Any (which is explained in better detail here).
So Any can't be extended. Is there any other language construct I can use to make it so that I can implement something like Kotlin's let
? Basically:
<expression>.foo { <expressionResult> in ... }
As a bonus/aside question, I think even if there is a way (I do hope there is just so I can learn), it won't be the same, because the Kotlin one can be used for control flow because I can do a non local return from the Kotlin one, but not from a Swift closure. Is that also correct?
CLARIFICATION
Basically, I can implement the Kotlin let
pattern for designated types:
protocol Cullable {}
extension Cullable {
func cull<R>(_ block:(Self) -> R) -> R {
return block(self)
}
}
extension Int:Cullable { }
42.cull { thing in print(thing) } // this will print 42
This works as I want. But I don't want to have to extend every single non-nominal type in the system to make it work. I just want to define it globally some how. If it was possible.