3

I have an error in using a Swift class. When I am trying to create a new object like so

let prod_obj = Produs(nume: nume_prod, cod_bare: cod_ext)

I get the error "Argument passed to call that takes no arguments" and I don't know why. I've read some docs and this is the exact same way they do it. This is how my class looks:

class Produs {
    var nume: String!
    var cod_bare: String!
}

I am thinking I might need to add an initializer but I don't see why that is necessary in my case.

jscs
  • 63,694
  • 13
  • 151
  • 195
MrEye
  • 35
  • 1
  • 8

3 Answers3

3

You can get the synthesized init using an Struct, like so

struct Produs {
    let nume: String
    let codBare: String
}
let prodObj = Produs(nume: numeProd, codBare: codBare)

For a class you either provide an initializer:

class Produs {
    var nume: String
    var codBare: String

    init (nume: String, codBare: String) {
        self.nume = nume
        self.codBare = codBare
    }
}
let prodObj = Produs(nume: numeProd, codBare: codBare)

Or

class Produs {
    var nume: String!
    var codBare: String!
}

let prodObj = Produs()
prodObj.nume = numeProd
prodObj.codBare = codBare

Note: Avoid using underscores in variable names, use camelCase such as codBare

AamirR
  • 11,672
  • 4
  • 59
  • 73
2

From the Structures and Classes chapter of the Swift book:

Memberwise Initializers for Structure Types All structures have an automatically generated memberwise initializer, which you can use to initialize the member properties of new structure instances. Initial values for the properties of the new instance can be passed to the memberwise initializer by name:

let vga = Resolution(width: 640, height: 480)

Unlike structures, class instances don’t receive a default memberwise initializer. Initializers are described in more detail in Initialization.

Your class has no initializer other than the default one with no parameters.

Either add the needed initializer with two parameters or change your class to a struct.

Robert Dresler
  • 10,580
  • 2
  • 22
  • 40
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • I suspected this might be it, but wasn't quite sure of it. I'll look into it. Thank you for the swift response! – MrEye Mar 19 '19 at 16:55
  • Another gotcha is that if the struct has private vars etc, it won't have auto generated initializer. – Jonny Aug 11 '22 at 08:19
0

You get the synthesized init with params only on structs. On classes you get the init() if you provide default values for properties otherwise you have to implement it.

Fabio Felici
  • 2,841
  • 15
  • 21