我想设置一个盒子阵列,每个盒子都有一个名称和物理尺寸以及周围的不确定性。我创建了以下课程:
struct PhysUnit {
var Mean: Double = 0.0
var Sigma: Double = 0.0
}
class Box {
var Name: String = "null"
var Width: PhysUnit = (Mean = 0.0 , Sigma = 0.0)
var Depth: PhysUnit
var Height: PhysUnit
}
func setupShelves() {
var A1Box = box()
A1Box.name = "A1"
A1Box.Width.Mean = 40.0
A1Box.Width.Sigma = 0.5
//etc
shelves.append(A1Box)
return }
但是如何初始化Box类?我尝试了许多方法,例如所示的示例,但是没有任何效果。
答案 0 :(得分:0)
您编写box()。试试这个:var A1Box = Box()
答案 1 :(得分:0)
您的代码中有一些错误。
Box
,而不是box
。结构可能更适合您的模型:
struct PhysUnit {
var Mean: Double = 0.0
var Sigma: Double = 0.0
}
struct Box {
var Name: String?
var Width: PhysUnit
var Depth: PhysUnit
var Height: PhysUnit
}
func setupShelves() {
var A1Box = Box(Name: "A1", Width: PhysUnit(Mean: 40, Sigma: 0.5), Depth: PhysUnit(), Height: PhysUnit())
shelves.append(A1Box)
}
但是如果您坚持使用类,则可以执行以下操作:
struct PhysUnit {
var Mean: Double = 0.0
var Sigma: Double = 0.0
}
class Box {
var Name: String?
var Width: PhysUnit
var Depth: PhysUnit
var Height: PhysUnit
init(Name: String?, Width: PhysUnit, Depth: PhysUnit, Height: PhysUnit) {
self.Name = Name
self.Width = Width
self.Depth = Depth
self.Height = Height
}
}
func setupShelves() {
var A1Box = Box(Name: "A1", Width: PhysUnit(Mean: 40, Sigma: 0.5), Depth: PhysUnit(), Height: PhysUnit())
shelves.append(A1Box)
}
答案 2 :(得分:0)
快速解答:
struct PhysUnit {
var mean: Double = 0.0
var sigma: Double = 0.0
}
class Box {
var name: String = "null"
var width: PhysUnit = PhysUnit()
var depth: PhysUnit?
var height: PhysUnit?
init() {}
}
func setupShelves() {
var A1Box = Box()
A1Box.name = "A1"
A1Box.width.mean = 40.0
A1Box.width.sigma = 0.5
...
shelves.append(A1Box)
}
几件事:
PhysUnit
具有默认值,因此您不需要
将其设置为var width
的默认值。编辑说明:我还更改了大小写,以匹配Swift最佳实践
答案 3 :(得分:0)
首先请遵守命名约定,即变量名以小写字母开头。
优良作法是使用默认值编写初始化程序,而不是直接将其分配给属性
struct PhysUnit {
var mean: Double
var sigma: Double
init(mean : Double = 0.0, sigma: Double = 0.0) {
self.mean = mean
self.sigma = sigma
}
}
class Box {
var name : String
var width : PhysUnit
var depth : PhysUnit
var height : PhysUnit
init(name : String, width : PhysUnit = PhysUnit(), depth : PhysUnit = PhysUnit(), height : PhysUnit = PhysUnit()) {
self.name = name
self.width = width
self.depth = depth
self.height = height
}
}
func setupShelves() {
let a1Box = Box(name: "A1", width: PhysUnit(mean: 40.0, sigma: 0.5))
shelves.append(a1Box)
}
答案 4 :(得分:-1)
你在这里...
struct PhysUnit {
var Mean: Double = 0.0
var Sigma: Double = 0.0
}
class Box {
var Name: String?
var Width = PhysUnit()
var Depth: PhysUnit?
var Height: PhysUnit?
}
func setupShelves() {
var A1Box = Box()
A1Box.Name = "A1"
A1Box.Width.Mean = 40.0
A1Box.Width.Sigma = 0.5
}
这里的代码有很多问题。如果您做过Swift教程,可能会有所帮助。