iOS Swift命名空間

Swift的命名空間是以模塊來(lái)劃分的,一個(gè)模塊表示一個(gè)命名空間,我們進(jìn)行APP開發(fā)是,默認(rèn)添加到主target的內(nèi)容是同處于同一個(gè)命名空間的。如果用Cocoapod的方式導(dǎo)入的第三方庫(kù),是以一個(gè)單獨(dú)的target存在,不會(huì)存在命名沖突。如果是以源碼的方式導(dǎo)入工程中,很有可能發(fā)生命名沖突。所以,為了安全起見(jiàn),第三方庫(kù)都會(huì)使用命名空間這種方式來(lái)防止沖突。在Objective-C上沒(méi)有命名空間,一般是使用方法名前面加前綴的方式避免沖突。

以下是圖片加載庫(kù)Kingfisher的命名空間實(shí)現(xiàn)方式

public struct KingfisherWrapper<Base> {
    public let base: Base
    public init(_ base: Base) {
        self.base = base
    }
}

/// Represents an object type that is compatible with Kingfisher. You can use `kf` property to get a
/// value in the namespace of Kingfisher.
public protocol KingfisherCompatible: AnyObject { }

/// Represents a value type that is compatible with Kingfisher. You can use `kf` property to get a
/// value in the namespace of Kingfisher.
public protocol KingfisherCompatibleValue {}

extension KingfisherCompatible {
    /// Gets a namespace holder for Kingfisher compatible types.
    public var kf: KingfisherWrapper<Self> {
        get { return KingfisherWrapper(self) }
        set { }
    }
}

extension KingfisherCompatibleValue {
    /// Gets a namespace holder for Kingfisher compatible types.
    public var kf: KingfisherWrapper<Self> {
        get { return KingfisherWrapper(self) }
        set { }
    }
}

extension UIImage: KingfisherCompatible { }
extension UIImageView: KingfisherCompatible { }
extension UIButton: KingfisherCompatible { }

上段代碼已經(jīng)定義了命名空間:“kf”
以下是kf命名空間內(nèi)添加方法,并使用

extension KingfisherWrapper where Base: Image {
//為UIIMage動(dòng)態(tài)添加animatedImageData屬性
    private(set) var animatedImageData: Data? {
        get { return getAssociatedObject(base, &animatedImageDataKey) }
        set { setRetainedAssociatedObject(base, &animatedImageDataKey, newValue) }
    }

      //為UIIMage動(dòng)態(tài)添加scale計(jì)算屬性
    var scale: CGFloat {
        return 1.0
    }

//使用:
let img = UIImage()
let scale = img.kf.scale //獲取kf命名空間下的scale屬性

在學(xué)習(xí)swift中發(fā)現(xiàn),Data類型在swift中也是值類型
swift中值類型除了數(shù)值類型外,Array, Dictionary, String , Data, Struct, Enum 均為值類型
Mark:之后有時(shí)間做詳細(xì)解釋

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容