Swift 实用技巧
xxxixxxx

1. protocol + extension 初始化后直接配置相应属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
protocol XXXBuilder {}

extension XXXBuilder {
public func with(configure: (inout Self) -> Void) -> Self {
var this = self
configure(&this)
return this
}
}

extension NSObject: XXXBuilder {}

// 使用
let tipLab = UILabel().with { lab in
lab.textColor = .red
lab.backgroundColor = .black
}

2. Double 转 String,限制小数位数

1
2
3
4
5
extension Double {
func format(_ count: Int) -> String {
String(format: "%.\(count)f", self)
}
}
  • Post title:Swift 实用技巧
  • Post author:xxxixxxx
  • Create time:2021-06-05 16:13:00
  • Post link:https://xxxixxx.github.io/2021/06/05/100-Swift实用技巧/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments