Full Decent Full Decent - 11 months ago 39
Swift Question

How to use Swift struct implicit initializer?

Here is the code I have:

struct Algorithm {
let category: String = ""
let title: String = ""
let fileName: String = ""

let a = Algorithm(

The autocomplete shows the only valid initializer:

enter image description here

But I was expecting to use the implicit initializer like

Algorithm(category: "", title: "", fileName: "")

This gives the error:

Argument passed to call that takes no arguments

There are even screenshots on another issue that shows this call being successfully used.

What am I doing wrong?


The problem is the let. If you declare your properties with var, you'll get the memberwise initializer:

struct Algorithm {
    var category: String = ""
    var title: String = ""
    var fileName: String = ""
let alg = Algorithm(category: "", title: "", fileName: "")

But since you supplied default values for all the properties, you don't get the memberwise initializer for let properties. The rule is that you get the implicit memberwise initializer for stored properties without a default value and for var properties (provided you have no explicit declared initializer).