0

I'm new to Swift and is trying to learn the concept of Memberwise Initialisers. The statement below came from "The Swift Programming Language 2.1".

My question is, under what kind of circumstance, a stored property in a structure would not have a default values? A example with explanation would be greatly appreciated.

Memberwise Initializers for Structure Types

Structure types automatically receive a memberwise initializer if they do not define any of their own custom initializers. Unlike a default initializer, the structure receives a memberwise initializer even if it has stored properties that do not have default values.

halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137

2 Answers2

1

For example when there is no sensible default value:

struct GeoLocation {
  let latitude: Float
  let longitude: Float
}

let geoLocation = GeoLocation(latitude: 13.7522, longitude: 100.4939)

There's many points on Earth, none may make sense to be the default in your app.

Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
1
struct Human {
    var legs = 2
    var name: String
}

is a structure where name does not have a default value. You can't have the default initializer Human(), because you can't provide the name; but you can use the memberwise initializer Human(legs: 1, name: "Lame Harry").

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • I thought var name: String is initialised to the default value of 'nil'? – Thor Feb 03 '16 at 02:20
  • 1
    No, `String` can't be `nil`. `String?` would have a default value of `nil`. – Amadan Feb 03 '16 at 02:21
  • Thanks for the clarification!! really appreciate your help! – Thor Feb 03 '16 at 02:22
  • 1
    The point there is the initialiser will not allow you to omit the legs parameter even with a default value – Leo Dabus Feb 03 '16 at 02:22
  • 1
    With a method you would be able to do not pass a parameter if you define a default value – Leo Dabus Feb 03 '16 at 02:23
  • 2
    @LeoDabus: No, while what you say is correct (since the memberwise initialiser takes all the properties in order), the point (of the quote, at least) is that if there are any stored properties without a default, you get the memberwise initializer, but not the default one, provided automatically for you. If you provide a custom initializer, you can do whatever the heck you want. – Amadan Feb 03 '16 at 02:24
  • 3
    If you change the legs declaration to `let legs = 2` it automatically drops its initializer – Leo Dabus Feb 03 '16 at 02:26
  • 2
    @LeoDabus: Yes, good catch, if you make `legs` a constant with a default value, then you can't initialize it again, so it doesn't get included in the memberwise initializer. – Amadan Feb 03 '16 at 02:30