用面向協(xié)議加載xib
- 創(chuàng)建一個協(xié)議類NibLoadable
import UIKit
protocol NibLoadable {
}
extension NibLoadable where Self : UIView {
static func loadFromNib(_ nibname : String? = nil) -> Self {
let loadName = nibname == nil ? "\(self)" : nibname!
return Bundle.main.loadNibNamed(loadName, owner: nil, options: nil)?.first as! Self
}
}
- 假如HintCoverView從xib那邊加載那么只需要遵守NibLoadable協(xié)議
class HintCoverView: UIView,NibLoadable{
}
- 調(diào)用時候:
lazy var hintCoverView : HintCoverView = {
let hintCoverView = HintCoverView.loadFromNib()
return hintCoverView
}()
這就是面向協(xié)議開發(fā),誰需要這個功能就遵守這個協(xié)議,其開發(fā)核心是: 模塊化(組件化),比如寫一個振動的動畫協(xié)議,如果當UITextField文本驗證錯誤時候需要振動,那么就繼承這個協(xié)議,如果除了振動還需要旋轉(zhuǎn),那么可再寫一個旋轉(zhuǎn)協(xié)議去繼承。這就是他功能強大之處。
面向協(xié)議進行網(wǎng)絡(luò)請求
import Foundation
protocol Requestable {
var method : HttpMethod { get }
var URLString : String { get }
associatedtype ResultType : Decodable
}
extension Requestable {
func request(completion : @escaping (ResultType?) -> Void) {
// 1.創(chuàng)建URL
let url = URL(string: URLString)!
// 2.創(chuàng)建request對象
let request = URLRequest(url: url)
// 3.通過URLSession發(fā)送請求
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, _, error) in
// 通過Decodable協(xié)議得到data數(shù)據(jù),手動調(diào)用ResultType的parse:方法獲得解析后的數(shù)據(jù)
completion(ResultType.parse(data!))
})
// 4.發(fā)起請求
task.resume()
}
}
// 解析數(shù)據(jù)協(xié)議
protocol Decodable {
static func parse(_ data : Data) -> Self?
}
- 假如有一個用戶信息請求:UserRequest,通過Requestable協(xié)議就會將里面參數(shù)傳進去再去調(diào)用請求的方法
class UserRequest : Requestable {
var method: HttpMethod = .GET
var URLString : String = "http://www.baidu.com"
typealias ResultType = User
}
- 用戶模型解析
import UIKit
struct User {
var name : String = "aaa"
var message : String = "bbb"
init?(data : Data) {
guard let dictT = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String : Any] else {
return nil
}
let dict = dictT?["args"] as? [String : Any]
guard let name = dict?["username"] as? String else {
return nil
}
guard let message = dict?["age"] as? String else {
return nil
}
self.name = name
self.message = message
}
}
// User(ResultType)的parse:方法進行數(shù)據(jù)解析
extension User : Decodable {
static func parse(_ data: Data) -> User? {
return User(data: data)
}
}
- 調(diào)用:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
UserRequest().request { (user : User?) in
if let user = user {
print(user.name, user.message)
}
}
}
}