I'm trying to build a swift script but I got stuck with this error:
./1.swift:10:11: error: use of instance member 'thisIsmyFunction' on type 'myScript'; did you mean to use a value of type 'myScript' instead?
 myScript.thisIsmyFunction()
 ~~~~~~~~ ^
Here is my code:
#!/usr/bin/swift
import Foundation
class myScript {
    func thisIsmyFunction() {
        print("Do something in there!")
    }
}
myScript.thisIsmyFunction()
What I'm trying to do is access to the function and execute the print.
Any of you knows what I'm doing wrong?
I'll really appreciate your help.
Unless otherwise specified, a member declared within a class is an instance member. So instanceInteger and instanceMethod are both instance members. The runtime system creates one copy of each instance variable for each instance of a class created by a program.
Instance Variable cannot have a Static modifier as it will become a Class level variable. Meaning STATIC is one of the keyword which cannot be used with Instance variable. The instance variable will get a default value, which means the instance variable can be used without initializing it.
You can only call an instance method on an instance of a class. For example, you would have to create an instance of myScript, then call it:
let script = myScript()
script.thisIsmyFunction()
You can also choose to make thisIsmyFunction a class method (which is formally known as a "type method" in Swift), and call it like the way you are doing right now:
class func thisIsmyFunction() {...}
Note the class modifier in front of func. Of course, this means you can't access self inside the function, because there is no longer an instance of the class.
For more information, see the Swift documentation on methods.
Aside: Swift classes should start with capital letters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With