swift 中 also 使用技巧
14 August 2025
Swift 中 also 使用技巧
also 定义
protocol Also {}
extension Also where Self: Any {
@discardableResult
func also(_ block: ((Self) -> Void)) -> Self {
block(self)
return self
}
}
extension NSObject: Also {}
使用示例
label = UILabel().also {
$0.font = .systemFont(ofSize: 12)
$0.textColor = .white
$0.numberOfLines = 1
captionView.addSubview($0)
}
