Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift optional values during initialization preventing default initializer inheritance

In Swift:

1) If you provide a default value for all of the stored properties in a class, then you inherit the default initializer, ie - init().

-- AND --

2) A property of any optional type defaults to the value of nil, ie - var shouldBeNill: String? //should initially be nill

-- THEREFORE --

I would expect this code to work:

class Product {
    let name: String?
}

let product = Product()

But when I type it in as a playground, I get the error: "class Product has no initializers".

Why isn't Product inheriting the default initializer init()? I know I can make this work by explicitly setting let name: String? = nil, but I'm unsure why I have to do this. Is this an error on Swift's side, or is there something I am not quite grasping?

like image 899
jneighbs Avatar asked Feb 09 '23 22:02

jneighbs


1 Answers

You are on the right track. The issue here is actually the let vs var.

let declares the property constant. In this case Product would have an optional constant name of type String with no initial value, and this of course makes no sense.

The compiler complains about a lacking init() function because let properties are allowed to be set once during init(), as part of object construction, if not defined already in declaration eg.

let name: String = "Im set!" // OK
let name: String? = nil // OK, but very weird :) 
let name = "Im set!" // OK, type not needed, implicit.
let name: String // OK, but needs to be set to a string during init()
let name: String? // OK, but needs to be set to string or nil during init()

let name // Not OK

The Swift Programming Language - Constants and Variables

like image 200
Mikael Hellman Avatar answered Feb 12 '23 12:02

Mikael Hellman