Jebus Jebus - 4 months ago 5
Swift Question

Instance member cannot be used on type Array

I have the below class and I use a function math to search the string in both SongTitle and in ESongTitle.

class KeerthanaiArray: NSObject {
var SongTitle: String = String()
var SongLyrics: String = String()
var ESongTitle: String = String()

init(SongTitle: String, SongLyrics:String, ESongTitle: String) {
self.SongTitle = SongTitle
self.SongLyrics = SongLyrics
self.ESongTitle = ESongTitle
}

class func match(string:String) -> Bool {
return SongTitle.containsString(string) || ESongTitle.containsString(string)
}
}


I get the error message 'Instance member SongTitle cannot be used on type 'Keerthanaiarray'. Please help

I need to declare the math func as class as I need to use the math function outside of its class

Answer

There are several problems here.

  1. This class KeerthanaiArray is not an array (as suggested by the name instead)
  2. Why are you extending NSObject?
  3. The class method match makes no sense, it is using 2 properties (SongTitle and ESongTitle) that does not exists in this context because they belongs to an instance of the class.

So let's cleanup your code

struct Song {
    let title: String
    let lyrics: String
    let eTitle: String

    func match(keyword: String) -> Bool {
        return title.containsString(keyword) || eTitle.containsString(keyword)
    }
}

I make you class a struct because makes more sense. You are free to turn back to class. If you stay on structs please keep in mind they are value types.

Now given a list of Song(s)

let songs: [Song] = ...

and a keyword

let keyword = "The Great Gig In the Sky"

this is how we search the array

let results = songs.filter { $0.match(keyword) }

Case insensitive version

struct Song {
    let title: String
    let lyrics: String
    let eTitle: String

    func match(keyword: String) -> Bool {
        let lowerCaseKeyword = keyword.lowercaseString
        return title.lowercaseString.containsString(lowerCaseKeyword) || eTitle.lowercaseString.containsString(lowerCaseKeyword)
    }
}
Comments