defer
- 将延迟至当前作用域结束之前执行
- throws、return之前会执行
fatalError
- 直接抛出错误,结束程序
溢出运算符Overflow Operator
&- 、 &+ 、&*
运算符重载
自定义运算符
中缀自定义
infix operator +-+ : AdditionPrecedence
struct Point {
var x : Int, y: Int
static func +-+(left:Point,right:Point) -> Int {
return (left.x+right.x)-(left.y+right.y)
}
}
指针的pointee
获取指向某个变量的指针
获取指向堆空间实例的指针
通配符
重写switch case判断逻辑 ( ~= )
条件编译
打印
参考:https://docs.swift.org/swift-book/ReferenceManual/Attributes.html
KVO KVC
@objc dynamic 修饰对应属性 ```swift class WuObserver: NSObject {
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print(change?[NSKeyValueChangeKey.oldKey]! )
} } class People: NSObject {
@objc dynamic var str = “init” var obs = WuObserver() var observation:NSKeyValueObservation?
override init() {
super.init()
addObserver(obs, forKeyPath: "str", options: [.new,.old], context: nil)
//或者通过block
observation = observe(\People.str, options: .new, changeHandler: { (obser, change) in
print(change,obser)
})
} }
<a name="aSnpq"></a>
# 利用关联对象,为class扩展储存属性
```swift
class People {}
extension People {
private static var NAME_KEY: Void?
var name : String {
set {
objc_setAssociatedObject(self, &People.NAME_KEY, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
get {
return (objc_getAssociatedObject(self, &People.NAME_KEY) as? String) ?? ""
}
}
}
let pp = People()
pp.name = "yuan"
print(pp.name)