I can not understand it is possible to use extensions with classes?

for example, I have this code:

extension HelloEveryBody { func addString() -> String { return "hhhh \(self)" } } class HelloEveryBody { var abc = "hello" func helloAgain() { print(abc.addString()) } } var test = HelloAgain() test.helloAgain() 

Why is this code not working?

    1 answer 1

    There in the compiler errors everything is explained

    one)

     print(abc.addString()) 

    abc is a string (of type String), the string does not have an addString function (this is a function of your HelloEveryBody class)

    2)

     var test = HelloAgain() 

    There is no HelloAgain class in your program (at least in the part you showed up). Apparently you wanted to create an object of the HelloEveryBody class.

    Well, to make it all work, you can rewrite for example so

     class HelloEveryBody { var abc = "hello" func helloAgain() { print(self.addString()) } } extension HelloEveryBody { func addString() -> String { return "hhhh \(self.abc)" } } var test = HelloEveryBody() test.helloAgain() 
    • yess! i can seee .... - jcmax