ioskaveen
ioskaveen

Reputation: 196

Cannot invoke initializer for type with no arguments - Swift

I'm moving from objective-c to swift and all i'm trying to do is simply create an instance of class so that I can access a property on said class.

var myClassInstance = MyClass()

print("length is \(myClassInstance.variableOne)")

something in that regard but I'm getting an error Cannot invoke initializer for type 'MyClass' with no arguments

Upvotes: 5

Views: 15534

Answers (1)

Khundragpan
Khundragpan

Reputation: 1960

You can create class like below:

class MyClass{
var variableOne:CGPoint

    init(variableOne: CGPoint) {
        self.variableOne = variableOne
    }

    convenience init () {
        self.init(variableOne: CGPoint(x: 0, y: 0))
    }
}


var myClassInstance = MyClass()
print("Default length is \(myClassInstance.variableOne)")

var myClassInstance2 = MyClass(variableOne: CGPoint(x: 10, y: 10))
print("length is \(myClassInstance2.variableOne)")

Upvotes: 8

Related Questions