4

I am new to Swift and following the online documentation. Specifically I'm looking at Initialization (https://docs.swift.org/swift-book/LanguageGuide/Initialization.html).

Under the sub-heading 'Memberwise Initializers for Structure Types', it says:

When you call a memberwise initializer, you can omit values for any properties that have default values. In the example above, the Size structure has a default value for both its height and width properties. You can omit either property or both properties, and the initializer uses the default value for anything you omit

and then provides an example:

struct Size {
    var width = 0.0, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)

let zeroByTwo = Size(height: 2.0)
print(zeroByTwo.width, zeroByTwo.height)
// Prints "0.0 2.0"

let zeroByZero = Size()
print(zeroByZero.width, zeroByZero.height)
// Prints "0.0 0.0"

If I try that, however, I get an error for the initialization of zeroByTwo:

Cannot invoke initializer for type 'Size' with an argument list of type '(height: Double)'

Have I misunderstood something?

I am using Swift 5.

2
  • That code works just fine for me in a Swift playground. What version of Xcode are you using? Commented Jun 13, 2019 at 18:01
  • 3
    That requires Swift 5.1 (Xcode 11 beta) Commented Jun 13, 2019 at 18:05

1 Answer 1

5

You've quoted from the Swift 5.1 version of the Swift Programming Language guide. The Swift 5 guide is missing that whole paragraph, because the feature is new to 5.1.

In Swift 5, the memberwise initializer includes all stored properties with no regard to default variable values, so you are forced to include every argument when creating a new instance (unless you create your own initializers).

In Swift 5.1 the memberwise initializer includes any default values, so you can opt to omit these arguments when you create an instance. You can read more about the new feature here: Synthesize default values for the memberwise initializer.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.