With 是一个 Swift 微型库,它提供了一个 with
语句——其模型仿照了 Python、JavaScript、Visual Basic、Object Pascal、Delphi 中的 with
功能;C# 中的 using
功能;以及 Kotlin 中的 also
/let
功能。
With 提供了一组重载的泛型自由函数,这些函数适用于:
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) { layer in
layer.borderWidth = 1.0
layer.borderColor = UIColor.white.cgColor
layer.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)
}