简体   繁体   中英

Under what kind of circumstance would a stored property in a structure not have a default value?

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.

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.

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") .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM