我发现了这个有用的子弹:
infix operator • {precedence 255}
/// Used when you'd normally use the dot operator to get a property,
/// but you have to store that operation as a closure for whatever reason.
///
///- Parameter instance: instance on which you'd normally use a dot
///- Parameter property: returns a Property when supplied with an instance
///
///- Returns: the property
///
///- Remark: Hold option, press 8
///
///- Note: Swift's "instance methods" are a lot like this.
/// They're really static methods that take an instance as their first parameter.
func •<Any, Property>(
instance: Any,
@noescape property: (of: Any) -> Property
) -> Property {
return property(of: instance)
}
这是一个用例:
import UIKit
public struct Setting<Value: AnyObject> {
init(key: String, defaultValue: Value) {
self.key = key
NSUserDefaults.standardUserDefaults().registerDefaults(
[key: defaultValue]
)
NSUserDefaults.standardUserDefaults().synchronize()
}
private let key: String
///- Returns: **value**
///- Parameter getter: The method of `NSUserDefaults` that returns a **`Value`**,
/// when supplied with a key that is a `String`
private func value<Value>(
getter value: NSUserDefaults -> (`for`: String) -> Value
) -> Value {
return (NSUserDefaults.standardUserDefaults()•value)(`for`: key)
}
///- Returns: The setter for **value**
///- Parameter setter: The method of `NSUserDefaults` that writes a **`Value`**,
/// for a key that is a `String`
private func value_set<Value>(value: Value,
setter set: NSUserDefaults -> (Value, `for`: String) -> ()
) {
(NSUserDefaults.standardUserDefaults()•set)(value, `for`: self.key)
}
}
extension Setting where Value: BooleanLiteralConvertible {
var value: Bool {
get {return value(getter: NSUserDefaults.boolForKey)}
set {value_set(newValue, setter: NSUserDefaults.setBool)}
}
}
extension Setting where Value: IntegerLiteralConvertible {
var value: Int {
get {return value(getter: NSUserDefaults.integerForKey)}
set {value_set(newValue, setter: NSUserDefaults.setInteger)}
}
}
看看我需要多多括号?我想要这个:
return NSUserDefaults.standardUserDefaults()•value(`for`: key)
NSUserDefaults.standardUserDefaults()•set(value, `for`: self.key)