With
With 是一个 Swift 微型库,它提供了一个 with
语句—— 这种语句的功能模仿了 Python、JavaScript、Visual Basic、Object Pascal、Delphi 中的 with
功能;C# 中的 using
;Kotlin 中的 also
/let
。
With 提供了一套重载的泛型自由函数,这些函数对于
- 以声明性风格初始化和设置对象或值很有用(想想 Swift UI 的层次化风格,但是适用于任何地方和任何事情)。
- 在对通过方法/属性获取的对象/值执行多个操作时,同时保持 D.R.Y 并不需要创建局部变量 (同时仍然避免重复调用方法/访问器)。
- 对仅需存在足够长的时间进行配置并进行一些计算的对象/值进行计算(并且你只对结果对象/值感兴趣)。
With 提供了一个自由函数 func with(_ subject: SubjectT, operations: (inout SubjectT) -> Void) -> SubjectT
,可以使用该函数对任何对象或值类型执行此类操作
// initializes a value-type `hitTestOptions` dictionary for use with
// `SCNView`'s `hitTest(…)` with the desired options some of which have
// changed in newer OS versions (which the standard dictionary literal syntax
// can't cleanly do)
let hitTestOptions = with([SCNHitTestOption : Any]()) {
$0[.boundingBoxOnly] = true
$0[.rootNode] = _myRootNode
if #available(iOS 11.0, tvOS 11.0, macOS 10.13, *) {
$0[.searchMode] = SCNHitTestSearchMode.all.rawValue
} else {
$0[.sortResults] = true
$0[.firstFoundOnly] = false
}
}
或者这样
// initializes the object-type `newButton` with title, sizing, styling, etc.
// and adds the view to a superview
let newButton = with(UIButton(type: .system)) {
$0.titleLabel!.font = .systemFont(ofSize: 13)
$0.setTitle("My Button", for: .normal)
$0.autoresizingMask = [ .flexibleLeftMargin, .flexibleBottomMargin ]
$0.contentEdgeInsets = UIEdgeInsets(top: 6.5, left: 7, bottom: 6.5, right: 7)
with($0.layer) {
$0.borderWidth = 1.0
$0.borderColor = UIColor.white.cgColor
$0.cornerRadius = 5
}
$0.sizeToFit()
rootViewController.view.addSubview($0)
}
With 还有一个不同的 func withMap(_ subject: SubjectT, operations: (inout SubjectT) -> ReturnT) -> SubjectT
形式,可以从闭包中返回任意值(而不是传入的值)
// initializes a `DateFormatter`, configures it, and uses it to calculate a
// `String` which is the only thing we want to hang onto
let dateString = withMap(DateFormatter()) {
$0.dateStyle = .medium
$0.timeStyle = .none
$0.locale = Locale(identifier: "en_US")
let currentDate = Date()
return $0.string(from: currentDate)
}