Edoardo de Cal Edoardo de Cal - 2 years ago 107
Swift Question

How do I access to a method of a class of a class in Swift?

My goal is to access a method

sayName()
contained in a class
Klass
inside another class
Manny
.

class Manny {
class Klass {
func sayName() {
print("Klass")
}
}
}


Writing
Manny.Klass.sayName()
returns an error because it expects some code inside the parentheses:


Missing argument for parameter #1 in call


Though, the method
sayName()
doesn't have any parameters.

I know I can send messages to a class
Manny
with the dot-notation
Manny.myMethod()
, but how do I access to a method of a class inside another class?

Answer Source

Your problem is that your function sayName() is an instance function, not a class function. Therefore without an instance of the class Klasse you cannot call the method.

Either change the type of the function to be of class type or create an instance first and call the function on that instance:

class Manny {
    class Klass {
        class func sayName() {
            print("Klass")
        }
    }
}

Manny.Klass.sayName()

OR

class Manny {
    class Klass {
        func sayName() {
            print("Klass")
        }
    }
}

let klasse = Manny.Klass()
klasse.sayName()

Both correctly print

Klass

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download