gpt4 book ai didi

swift - 具有许多属性的初始化类

转载 作者:搜寻专家 更新时间:2023-10-31 22:32:26 25 4
gpt4 key购买 nike

我正在学习 Swift,目前正在复习初始化器。我创建了一个具有简单继承类关系的测试项目。我为每个类设置了 10 个属性,一切正常。但是,我觉得我遗漏了一些东西,它看起来太长太乱(特别是 ClassB init),有什么线索可以缩短我的代码同时保持它的一致性吗?

A 类:

class ClassA: NSObject {

var a1: Int
var a2: Int
var a3: Int
var a4: Int
var a5: Int
var a6: Int
var a7: Int
var a8: Int
var a9: Int
var a10: Int

init (a1: Int, a2: Int, a3: Int, a4: Int, a5: Int, a6: Int, a7: Int, a8: Int, a9: Int, a10: Int) {
self.a1 = a1
self.a2 = a2
self.a3 = a3
self.a4 = a4
self.a5 = a5
self.a6 = a6
self.a7 = a7
self.a8 = a8
self.a9 = a9
self.a10 = a10
}
}

B 类:

class ClassB: ClassA {

var b1: Int
var b2: Int
var b3: Int
var b4: Int
var b5: Int
var b6: Int
var b7: Int
var b8: Int
var b9: Int
var b10: Int

init (a1: Int, a2: Int, a3: Int, a4: Int, a5: Int, a6: Int, a7: Int, a8: Int, a9: Int, a10: Int, b1: Int, b2: Int, b3: Int, b4: Int, b5: Int, b6: Int, b7: Int, b8: Int, b9: Int, b10: Int) {
self.b1 = b1
self.b2 = b2
self.b3 = b3
self.b4 = b4
self.b5 = b5
self.b6 = b6
self.b7 = b7
self.b8 = b8
self.b9 = b9
self.b10 = b10
super.init(a1: a1, a2: a2, a3: a3, a4: a4, a5: a5, a6: a6, a7: a7, a8: a8, a9: a9, a10: a10)
}
}

最佳答案

一个可能的解决方案是使用结构和协议(protocol)而不是类和继承。在 Swift 中,使用 struct 为您创建默认初始化程序。

代码并没有那么短,但是你不需要再写 init() 了:

protocol A {
var a1: Int { get set }
var a2: Int { get set }
var a3: Int { get set }
var a4: Int { get set }
var a5: Int { get set }
var a6: Int { get set }
var a7: Int { get set }
var a8: Int { get set }
var a9: Int { get set }
var a10: Int { get set }
}

struct B: A {
var a1: Int
var a2: Int
var a3: Int
var a4: Int
var a5: Int
var a6: Int
var a7: Int
var a8: Int
var a9: Int
var a10: Int

var b1: Int
var b2: Int
var b3: Int
var b4: Int
var b5: Int
var b6: Int
var b7: Int
var b8: Int
var b9: Int
var b10: Int
}

关于swift - 具有许多属性的初始化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36878699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com