Search code examples
swiftclassinitializer

"Argument passed to call that takes no arguments" when creating an object


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.


Solution

  • 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