Swift中Set重载实现:简化元组集合操作的方法问询
实现简化的坐标集合操作方案
方案一:扩展Set<XY>实现方法重载
直接对Set进行扩展,约束元素类型为XY,添加接受x、y参数的insert和contains重载方法,原有Set<XY>类型即可直接使用简化调用:
// 先优化XY的初始化(可选但推荐,提升可读性) struct XY: Hashable { let x: Int let y: Int init(_ tuple: (Int, Int)) { x = tuple.0 y = tuple.1 } // 添加直接接收x、y的初始化方法 init(x: Int, y: Int) { self.x = x self.y = y } } // 扩展Set,约束元素为XY extension Set where Element == XY { mutating func insert(_ x: Int, _ y: Int) { insert(XY(x: x, y: y)) } func contains(_ x: Int, _ y: Int) -> Bool { contains(XY(x: x, y: y)) } }
使用示例:
var xyset: Set<XY> = [] xyset.insert(3, 1) xyset.insert(1, 1) let found = xyset.contains(1, 1) print(found) // 输出 true
方案二:自定义XYSet封装Set<XY>
如果需要独立的类型处理坐标集合,可以自定义XYSet结构体,内部持有Set<XY>并封装所需方法,这种方式能灵活控制对外暴露的功能:
struct XY: Hashable { let x: Int let y: Int init(_ tuple: (Int, Int)) { x = tuple.0 y = tuple.1 } init(x: Int, y: Int) { self.x = x self.y = y } } struct XYSet { // 内部持有Set<XY>作为存储核心 private var innerSet: Set<XY> = [] // 自定义insert方法 mutating func insert(_ x: Int, _ y: Int) { innerSet.insert(XY(x: x, y: y)) } // 自定义contains方法 func contains(_ x: Int, _ y: Int) -> Bool { innerSet.contains(XY(x: x, y: y)) } // 可按需封装其他Set功能,比如删除元素 mutating func remove(_ x: Int, _ y: Int) -> XY? { innerSet.remove(XY(x: x, y: y)) } // 暴露集合数量属性 var count: Int { innerSet.count } }
使用示例:
var xyset = XYSet() xyset.insert(3, 1) xyset.insert(1, 1) let found = xyset.contains(1, 1) print(found) // 输出 true print(xyset.count) // 输出 2
补充说明
Swift中Set是结构体,不支持继承,所以你最初设想的struct XYSet: Set<XY>写法不可行,必须通过**组合(内部持有Set实例)**的方式实现自定义集合类型。
内容的提问来源于stack exchange,提问作者nilgirian
相关产品推荐
相关产品推荐

