apply
, also
, let
, run
之類的好用的 Scope Functions// kotlin file
class Cat(){
var name = ""
}
fun main(args : Array<String>){
val cat = Cat()
cat.apply {
this.name = "喵的名字"
}
}
// in swift file ViewController
tableview.delegate = self
tableview.dataSource = self
tableview.reloadData()
// in swift file ViewController
tableview?.apply {
$0.delegate = self
$0.dataSource = self
$0.reloadData()
}
// swift file
import Foundation
protocol ScopeFunc {}
extension ScopeFunc {
@discardableResult
func also(block: (Self) -> ()) -> Self {
block(self)
return self
}
@discardableResult
func apply(block: (Self) -> ()) -> Self {
block(self)
return self
}
@discardableResult
func `let`<R>(block: (Self) -> R) -> R? {
return block(self)
}
@discardableResult
func run<R>(block: (Self) -> R) -> R? {
return block(self)
}
}
extension Optional where Wrapped: ScopeFunc { }
extension NSObject: ScopeFunc {}
extension Array: ScopeFunc {}
extension String: ScopeFunc {}
extension String.SubSequence: ScopeFunc {}
extension Int: ScopeFunc {}
extension Float: ScopeFunc {}
extension Double: ScopeFunc {}
extension Bool: ScopeFunc {}
apply
初始化了// in swift file ViewController
tableview?.apply {
$0.delegate = self
$0.dataSource = self
$0.reloadData()
}
ScopeFunc
裡面的 apply
跟 also
寫的一樣, let
和 run
寫的也一樣Basically, these functions do the same: execute a block of code on an object. What’s different is how this object becomes available inside the block and what is the result of the whole expression.
let
, also
裡面用是用 it
而 apply
, run
用的是 this
但這樣寫都只能用 $0
相當於 kotlin 的 it
啊, 那 this
哩lambda
裡面使用 self
會呼叫到外層的 class 實體, 所以我才使用 $0