Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: error: use of instance member on type

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.

like image 606
user2924482 Avatar asked May 05 '16 16:05

user2924482


People also ask

What is instance member in Swift?

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.

Which one of the key Cannot be used with instance variable?

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.


1 Answers

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.

like image 126
Dominic K Avatar answered Oct 12 '22 19:10

Dominic K