2

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?

0

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

5

You provided the default values for the properties that's why compiler won't add the default initialiser. When you remove the default values you will get what you are expecting:

struct Algorithm {
    let category: String
    let title: String
    let fileName: String
}

Comments

1

use

struct Algorithm {
    var category: String = ""
    var title: String = ""
    var fileName: String = ""
}

and autocomplete will show you both possibilities

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.