Swift Struct:在运行时添加新参数

时间:2019-03-05 09:55:53

标签: swift struct runtime

给出这样的struct实例:

struct Size {
    var width: Int
    var height: Int
}

是否可以通过运行时将其扩展为:

struct Size {
    var width: Int
    var height: Int
    var depth: Int
}

向Size结构的现有实例添加新参数?

谢谢

2 个答案:

答案 0 :(得分:1)

否,没有办法添加,但是您可以执行以下操作:您可以将运行时可能需要的所有内容声明为可选内容,再加上 但是,如果您能够在运行时向struct添加新属性,它有什么用?您将如何使用它们?

这些值只是可选的。

struct Size {
 var width: Int
 var height: Int
 var depth: Int? // this could be nil or Int 
}

答案 1 :(得分:0)

这是Swift。创建对象时,您应该了解对象的属性。

您必须选择:

  • 使var send = [{'latitude': widget.lat}, {'latitude': 123.456}]; 属性为可选。那么该属性不必具有任何值

    depth
  • 或为其提供默认值

    var depth: Int?
    

    使用第二个选项,您可以创建具有默认值的自定义var depth: Int = 1

    init