Swift中如何继承[MemoryComponent]数组类型并添加自定义存储属性
解决方案
首先明确两个Swift的语法限制:
- Swift 中的
Array是值类型(结构体),本身不支持继承 - Swift 扩展不允许添加存储属性,因此你之前的两种尝试都无法实现需求
推荐用组合封装的方式实现自定义集合,既可以固定元素类型为MemoryComponent,也能自由添加自定义存储属性:
基础简化实现
如果不需要完全兼容原生数组的所有API,只需要用到常用的增删改查操作,可以直接封装一个持有内部数组的自定义类/结构体:
// 假设你已有的MemoryComponent类 class MemoryComponent {} class StorageArray { // 内部持有原生数组存储元素 private var elements: [MemoryComponent] = [] // 你可以自由添加任意自定义存储属性 var customStorageProperty: String = "" var extraFlag: Bool = false // 按需实现你需要的数组常用能力 var count: Int { elements.count } subscript(index: Int) -> MemoryComponent { get { elements[index] } set { elements[index] = newValue } } func append(_ element: MemoryComponent) { elements.append(element) } func remove(at index: Int) -> MemoryComponent { elements.remove(at: index) } }
完全兼容原生集合API的实现
如果需要支持for-in遍历、map/filter等高阶函数,可以让自定义类遵守Collection(如果需要支持修改就遵守MutableCollection)协议:
class StorageArray: Collection, MutableCollection { typealias Element = MemoryComponent typealias Index = Int private var elements: [MemoryComponent] = [] // 自定义存储属性 var customProperty: Int = 0 // Collection协议必需实现的内容 var startIndex: Int { elements.startIndex } var endIndex: Int { elements.endIndex } func index(after i: Int) -> Int { elements.index(after: i) } subscript(position: Int) -> MemoryComponent { get { elements[position] } set { elements[position] = newValue } } // 还可以自由添加其他数组方法,或者直接转发到内部elements func append(_ newElement: MemoryComponent) { elements.append(newElement) } }
实现后你就可以像使用普通数组一样使用这个自定义类型,同时还能使用你添加的自定义存储属性。
如果你不需要引用类型的特性,也可以把
class换成struct,获得和原生Array一致的值类型行为。
内容的提问来源于stack exchange,提问作者Smally
相关产品推荐
相关产品推荐

