用面向協(xié)議加載xib
- 創(chuàng)建一個(gè)協(xié)議類(lèi)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)用時(shí)候:
lazy var hintCoverView : HintCoverView = {
let hintCoverView = HintCoverView.loadFromNib()
return hintCoverView
}()
這就是面向協(xié)議開(kāi)發(fā)桶错,誰(shuí)需要這個(gè)功能就遵守這個(gè)協(xié)議敞斋,其開(kāi)發(fā)核心是: 模塊化(組件化)扁耐,比如寫(xiě)一個(gè)振動(dòng)的動(dòng)畫(huà)協(xié)議,如果當(dāng)UITextField文本驗(yàn)證錯(cuò)誤時(shí)候需要振動(dòng),那么就繼承這個(gè)協(xié)議寻馏,如果除了振動(dòng)還需要旋轉(zhuǎn)兆龙,那么可再寫(xiě)一個(gè)旋轉(zhuǎn)協(xié)議去繼承。這就是他功能強(qiáng)大之處耻台。
面向協(xié)議進(jìn)行網(wǎng)絡(luò)請(qǐng)求
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對(duì)象
let request = URLRequest(url: url)
// 3.通過(guò)URLSession發(fā)送請(qǐng)求
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, _, error) in
// 通過(guò)Decodable協(xié)議得到data數(shù)據(jù)空免,手動(dòng)調(diào)用ResultType的parse:方法獲得解析后的數(shù)據(jù)
completion(ResultType.parse(data!))
})
// 4.發(fā)起請(qǐng)求
task.resume()
}
}
// 解析數(shù)據(jù)協(xié)議
protocol Decodable {
static func parse(_ data : Data) -> Self?
}
- 假如有一個(gè)用戶信息請(qǐng)求:UserRequest,通過(guò)Requestable協(xié)議就會(huì)將里面參數(shù)傳進(jìn)去再去調(diào)用請(qǐng)求的方法
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:方法進(jìn)行數(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)
}
}
}
}