Swift使用協議加泛型編程(一)

最近重構公司內部使用的PDT應用. 其中有一個模塊使用了協議加泛型重構了一下, 感受不錯.編程

本來代碼有4份很是相似的.swift

import Foundation

open class DeliveryRegionController: NSObject {

    internal(set) public var regions: [Region] = []
    
    public var selected: Region?
    
    private let loader: ((@escaping ([Region]) -> Void, @escaping ErrorHandler) -> Bool)?
    
    init(loader: @escaping (@escaping ([Region]) -> Void, @escaping ErrorHandler) -> Bool) {
        
        self.loader = loader
        
        super.init()
    }
    
    @discardableResult
    public func reload(completion: @escaping (DeliveryRegionController) -> Void, failure: @escaping ErrorHandler) -> Bool {
        
        if let loader = self.loader {
            return loader({ regions in
                self.regions = regions
                completion(self)
                
            }, failure)
        } else {
            completion(self)
            return false
        }
    }
}
複製代碼
import Foundation

open class DeliveryStationController: NSObject {

    internal(set) public var stations: [Station] = []
    
    public var selected: Station?
    
    private let loader: ((@escaping ([Station]) -> Void, @escaping ErrorHandler) -> Bool)?
    
    init(loader: @escaping (@escaping ([Station]) -> Void, @escaping ErrorHandler) -> Bool) {
        
        self.loader = loader
        
        super.init()
    }
    
    @discardableResult
    public func reload(completion: @escaping (DeliveryStationController) -> Void, failure: @escaping ErrorHandler) -> Bool {
        
        if let loader = self.loader {
            return loader({ stations in
                self.stations = stations
                completion(self)
                
            }, failure)
        } else {
            completion(self)
            return false
        }
    }
}
複製代碼

貼了兩份, 能夠發現除了數據類型, 其餘的幾乎如出一轍. 爲了提升代碼的複用性, 因而重構一下.api

最近有個朋友一直問我Swift協議相關的東西, 因而, 上面這些代碼, 我就用了協議加泛型來重構一下, 恰好還能夠給她講解一下.ui

首先根據以上代碼, 定義一份協議. 返回的類型定義了一個泛型Object.spa

public protocol ObjectLoader {
    
    associatedtype Object
    
    var objects: [Object] { get }
    
    var selected: Object? { get set }
    
    var loader: ((@escaping ([Object]) -> Void, @escaping ErrorHandler) -> Bool)? { get }
    
    func reload(completion: @escaping (Self) -> Void, failure: @escaping ErrorHandler) -> Bool
}
複製代碼

這裏reload方法裏面返回了Self, 這樣下面遵循這個協議的類, 就只能用final了, 若是不想用final, 就要稍微麻煩一些, 這裏就不做討論了.code

好了, 下面來實現具體的類.ci

public final class ObjectLoaderController<Object>: NSObject, ObjectLoader {
    
    fileprivate var _objects: [Object] = []
    
    fileprivate var _selected: Object?
    
    internal(set) open var objects: [Object] {
        get {
            return self._objects
        }
        set {
            self._objects = newValue
        }
    }
    
    open var selected: Object? {
        get {
            return self._selected
        }
        set {
            self._selected = newValue
        }
    }
    
    open let loader: ((@escaping ([Object]) -> Void, @escaping ErrorHandler) -> Bool)?
    
    init(loader: @escaping (@escaping ([Object]) -> Void, @escaping ErrorHandler) -> Bool) {
        self.loader = loader
        super.init()
    }
    
    @discardableResult
    public func reload(completion: @escaping (ObjectLoaderController) -> Void, failure: @escaping ErrorHandler) -> Bool {
        if let loader = self.loader {
            return loader({ objects in
                self._objects = objects
                completion(self)
                
            }, failure)
        } else {
            completion(self)
            return false
        }
    }
}
複製代碼

這樣重構完了之後, 使用就是用這個Loader就行了, 返回的類型在定義好了之後, Swift的自動推導類型能夠很方便的獲取到具體類型.get

由於數據的load我也使用了協議, 而且項目相關的緣由, make這個loader的方法就像下面這樣.it

public protocol DeliveryRegionLoader: class {
    
    func loadDeliveryRegion(completion: @escaping ([TRNameIdPair]) -> Void, failure: @escaping ErrorHandler) -> Bool
}

extension DeliveryRegionLoader where Self: EZFilter {
    
    public func makeDeliveryRegionController() -> ObjectLoaderController<Region>? {
        
        guard self.filterOptions.contains(.region) else { return nil }
        
        let controller = ObjectLoaderController { [weak self]completion, failure -> Bool in
            
            return self?.loadDeliveryRegion(completion: { result in
                
                completion(result.map { Region(pair: $0) })
            }, failure: failure) ?? false
            
        }
        return controller
    }
}
複製代碼

具體的load方法, 也是一個類遵循了上面DeliveryRegionLoader協議, 而後實現具體的方法.io

extension NHFilter: DeliveryRegionLoader {
    
    func loadDeliveryRegion(completion: @escaping ([TRNameIdPair]) -> Void, failure: @escaping ErrorHandler) -> Bool {
        
        DeliveryService.UserGetRegions(deliveryTypeId: self.deliveryMethod.id, success: { (result) in

            completion(result)

        }, failure: failure)
        
        return true
    }
}
複製代碼

以上, 就是傳說中的協議加泛型編程了, 其實並無那麼神祕...

相關文章
相關標籤/搜索