mirror of
https://github.com/NohamR/knowledge-kit.git
synced 2026-05-25 04:17:17 +00:00
update: 动态库、静态库的编译链接细节
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
# Swift 面向协议编程
|
||||
# Swift 面向协议编程
|
||||
|
||||
## 概念
|
||||
|
||||
@@ -125,8 +125,13 @@ extension MyCompitable {
|
||||
get{ MY<Self>.self }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
具体使用的地方
|
||||
```swift
|
||||
// 第一步:让 String 拥有 my 前缀属性
|
||||
extension String: MyCompitable { }
|
||||
// 第二步:给 String.my、String().my 前缀拓展功能(因为协议的 extension 中有 my 计算属性,也有个 my 静态计算属性,也就是一个方法)
|
||||
extension MY where Base == String {
|
||||
func countOfNumber() -> Int {
|
||||
var count: Int = 0
|
||||
@@ -156,4 +161,65 @@ I am a mutating method
|
||||
要拓展系统提供的类型,可以按照上述模版进行修改。
|
||||
|
||||
- 加前缀 `my` 的目的是防止重复,系统实现是黑盒,如果自己直接提供类似 `testString.countOfNumber` 怕后续系统也提供 `countOfNumber` 方法。所以加前缀 `testString.my.countOfNumber`
|
||||
-
|
||||
|
||||
QA:如果是 NSString、NSMutableString 可以满足需求吗?
|
||||
答案是不行的。但是可以按照上述方式进行修改调整。怎么修改?按照 `extension MY where Base == String` 和 `extension MY where Base == NSString` 的方式写2遍?
|
||||
|
||||
当然不,找共性,**String、NSString、NSMutableString 都遵循 ExpressibleByStringLiteral 协议**。所以实现 `extension MY where Base: ExpressibleByStringLiteral` 即可。
|
||||
|
||||
```swift
|
||||
// 第一步:让 String 拥有 my 前缀属性
|
||||
extension String: MyCompitable { }
|
||||
extension NSString: MyCompitable { }
|
||||
|
||||
// 第二步:给 String.my、String().my 前缀拓展功能(因为协议的 extension 中有 my 计算属性,也有个 my 静态计算属性,也就是一个方法)
|
||||
extension MY where Base: ExpressibleByStringLiteral {
|
||||
func countOfNumber() -> Int {
|
||||
var count: Int = 0
|
||||
for c in (base as! String) where ("0"..."9").contains(c) {
|
||||
count += 1
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
static func test() {
|
||||
print("I am a static method")
|
||||
}
|
||||
|
||||
mutating func modify() {
|
||||
print("I am a mutating method")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var str:String = "123"
|
||||
print(str.my.countOfNumber())
|
||||
String.my.test()
|
||||
str.my.modify()
|
||||
print("")
|
||||
|
||||
var ocStr: NSString = "456" as NSString
|
||||
print(ocStr.my.countOfNumber())
|
||||
String.my.test()
|
||||
ocStr.my.modify()
|
||||
print("")
|
||||
|
||||
var ocMutableStr: NSString = "456" as NSMutableString
|
||||
print(ocMutableStr.my.countOfNumber())
|
||||
String.my.test()
|
||||
ocMutableStr.my.modify()
|
||||
```
|
||||
|
||||
|
||||
这种设计在 SnapKit 中也存在:
|
||||
```swift
|
||||
// 实例属性用法
|
||||
view.my.makeConstraints { ... }
|
||||
// 静态属性用法
|
||||
UIView.my.registerDefaultConfig()
|
||||
```
|
||||
在 RxSwift 中也存在:
|
||||
```swift
|
||||
let observable = Observable<Int>.timer(.second(2), period: .second(1), scheduler: MainScheduler.instance)
|
||||
observable.map{ "\($0)" }.bind(to: priceLabel.rx.text)
|
||||
```
|
||||
Reference in New Issue
Block a user