user842225
user842225

Reputation: 5979

The computed properties & struct in my case

I am learning Swift, I saw some code from a project like following:

struct ServiceType {
    init(_ value: UInt)
    var value: UInt
}
var External: ServiceType { get }
var Internal: ServiceType { get }
var Normal: ServiceType { get }

I understand that the above code created three computed properties External, Internal & Normal all with type ServiceType.

What I want to ask are:

  1. Why the struct declaration declare a init() ? I didn't see this when I was reading a Swift programming book.

  2. What does it mean to have an underscore _ followed by a space before value: UInt in the init(_ value: UInt) ?

  3. Is it so that struct has a value property by default in Swift? The above code just explicitly set the type of value to UInt?

  4. What does the empty get mean in each property? What value it returns?

  5. Does the OS randomly assign UInt value to each property's value?

Upvotes: 0

Views: 763

Answers (1)

Qbyte
Qbyte

Reputation: 13243

1. A struct gets a default initializer if it doesn't provide one on its own:

struct ServiceType {
    var value: UInt
}

// default initialize with an specified parameter name "value" (called external name)
let service = ServiceType(value: 4)

In this case the struct provides an initializer so you don't get the default one.

2. The underscore says that you don't have an external name:

let service = ServiceType(4)

Replacing the underscore with a different name the name is now the external name:

struct ServiceType {
    init(aval value: UInt)
    var value: UInt
}

let service = ServiceType(aval: 4)

3. If I understand you right structs in general don't have a value property by default and in this case a value property is declared to be of type Uint. var value = 0 would be inferred to be of type Int.

4. If you have seen this code in a protocol { get } means that it only returns a value and does not set one ({ get set }).

The return value of these computed properties are all of type ServiceType.

5. In Swift you don't get default values for Ints, Doubles, ... as in other languages (mostly 0) except for Optionals which are nil by default. So you have to make sure that the value is initialized before using it otherwise the compiler will complain.

All of this gets pretty clear if you read the initialization chapter of the Swift book.

Upvotes: 1

Related Questions