0

I'm study the swift by the Apple's official book "The Swift Programming Language" and faced a compilation error. I create a structure which has two properties with default values. And attempt to initialise with only one parameter results in a compilation error. What a reason of it?

struct Size {
    var width = 0.0, height = 0.0
}

let twoByTwo = Size(width: 2.0, height: 2.0)
let zeroByTwo = Size(height: 2.0)
let zeroByZero = Size()
Ace Rodstin
  • 132
  • 1
  • 6
  • Please add more details and error – Romil Patel Jul 24 '19 at 05:28
  • 1
    That code requires Swift 5.1/Xcode 11 beta. – Martin R Jul 24 '19 at 05:41
  • Look at this https://stackoverflow.com/a/56683932/919545 for more info – Ankit Srivastava Jul 24 '19 at 05:42
  • Mohindra's answer below is the correct one. A side note to your code tho is that structs should never be mutable, hence you will always want to use `let` when declaring the values. And by looking at the naming i guess you want to use this for a `CGSize` in a later moment. Which then would be neat to create a computed property. `var size: CGSize {return CGSize(width: width, height: height)}` – Vollan Jul 24 '19 at 06:10

1 Answers1

1

In Swift whenever we are going to create a structure. Swift automatically creates the default initializer for the particular structure. In your case, you will get a compile-time error in let zeroByTwo = Size(height: 2.0).

enter image description here

Because you are not passing all the parameters required by the default initializer. to fix that issue you can create your own init() functions in your structure as shown below.

struct Size {
    var width:Double, height:Double

    init(width:Double = 0.0, height:Double = 0.0){
        self.width = width
        self.height = height
    }
}

let twoByTwo = Size(width: 2.0, height: 2.0)
let zeroByTwo = Size(width: 2.0)
let zeroByZero = Size()
Mohindra Bhati
  • 146
  • 1
  • 8
  • 1
    It's the correct answer, but you should edit it to make the init params have default values. To avoid multiple inits. As your approach is kinda Java'ish. And don't use images of code as answer. – Vollan Jul 24 '19 at 05:44
  • Still errors or at least warnings in the init as you have them as optionals and yet default value 0.0 – Vollan Jul 24 '19 at 05:55