Reputation: 796
Given an instance of struct like this:
struct Size {
var width: Int
var height: Int
}
Is there the possibility to extend it by runtime to:
struct Size {
var width: Int
var height: Int
var depth: Int
}
adding a new parameter to the existing instance of Size struct ?
Thanks
Upvotes: 1
Views: 1851
Reputation: 11200
This is Swift. You should know about properites of your object when you're creating it.
You have to options:
Make depth
property optional. Then this property doesn't have to have any value
var depth: Int?
Or give it default value
var depth: Int = 1
With this second option you can create custom init
with default value
struct Size {
var width, height, depth: Int
}
extension Size {
init(width: Int, height: Int) {
self.init(width: width, height: height, depth: 1)
}
}
Size(width: 1, height: 1)
Size(width: 1, height: 1, depth: 1)
Upvotes: 0
Reputation: 5088
No, there is no way adding that but what you can do is the following, You can declare everything that you might need at run time as an optional, plus
if however you were able to add new properties to the struct
at run time what is the use of it ? how are you going to use them ?.
Simply optional the values.
struct Size {
var width: Int
var height: Int
var depth: Int? // this could be nil or Int
}
Upvotes: 1