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ā)生命名沖突哎甲。所以蔫敲,為了安全起見,第三方庫(kù)都會(huì)使用命名空間這種方式來(lái)防止沖突炭玫。在Objective-C上沒有命名空間燕偶,一般是使用方法名前面加前綴的方式避免沖突。
以下是圖片加載庫(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ì)解釋