Rcub3161
Rcub3161

Reputation: 61

Instance Member Cannot be Used on Type For The Class NSObject

I am getting an error that displays the following message:

logoImage cannot be used on type 'Home'

I am confused as to why I am receiving this error message. Any help is greatly appreciated!

If you need more information to help answer the question, post a comment and I will get you the information you need.

Thank you in advance!

class Home: NSObject {

    var logoImage: [String] = [
         "apple.png",
         "Mango.png",
         "Strawberry.png",
         "Cat.png",
        ]

    class func homeDisplayImage() -> String  {
        for var i = 0; i < 3; i++ {
            return logoImage[i]
        }
    }
}

Upvotes: 1

Views: 1168

Answers (2)

Sllew
Sllew

Reputation: 68

If you want homeDisplayImage() to be a function of the Home class, take out the word 'class' from in front of it. You're also missing a closing brace. If you use this code it runs with no errors:

class Home: NSObject {
    var logoImage: [String] = [
        "apple.png",
        "Mango.png",
        "Strawberry.png",
        "Cat.png",
    ]

    func homeDisplayImage() -> String  {
        for var i = 0; i < 3; i++ {
            return logoImage[i]
        }
    }
}

Upvotes: 0

Unheilig
Unheilig

Reputation: 16292

In Java sense; static function cannot refer to non-static members. It is the same in Swift. Your logoImage is non-static whilst homeDisplayImage is a static function.

You would need to either drop the class from your function:

func homeDisplayImage() -> String  {
for var i = 0; i < 3; i++ {
    return logoImage[i]
}

or add a static to your var:

static var logoImage: [String] = [
    "apple.png",
    "Mango.png",
    "Strawberry.png",
    "Cat.png",
]

Upvotes: 4

Related Questions