引用由另一个函数

时间:2016-07-30 17:41:17

标签: ios arrays swift function reference

我有以下结构

struct KStruct {
let SongTitle: String
let SongLyrics: String
let ESongTitle: String

 init(SongTitle: String, SongLyrics:String, ESongTitle: String) {
    self.SongTitle =  SongTitle
    self.SongLyrics = SongLyrics
    self.ESongTitle = ESongTitle
}
func match(string:String) -> Bool {
    let lowerCaseKeyword = string.lowercaseString
    return SongTitle.lowercaseString.containsString(lowerCaseKeyword) || ESongTitle.containsString(lowerCaseKeyword)

    }
}

我正在将其转换为数组,并且我在viewDidload函数中的下面循环中填充此数组

let keerthanaiArray = KStruct(SongTitle : songTitleT!, SongLyrics : songLyricsT!,
                                    ESongTitle : EsongTitleT!)

现在我试图在另一个函数filterContentForSearchText中引用这个数组

但我无法这样做,因为数组在其自身功能之外无法识别。如何在另一个函数中读取此数组。请帮忙

1 个答案:

答案 0 :(得分:0)

将数组声明为全局数组。您的代码keerthanaiArray KStruct 类型对象,而不是数组。看看以下内容:

var keerthanaiArray:[KStruct]!

override func viewDidLoad() {
    super.viewDidLoad()
    if KeerthanaigalDB.open()
    {
        var i = 0
        let querySQL = "SELECT * FROM KEERTHANAIGAL ORDER BY ROWID DESC"
        let results:FMResultSet? = KeerthanaigalDB.executeQuery(querySQL, withArgumentsInArray: nil)
        if (results != nil)
        {
            while results!.next()
            {
                let songTitleT = results?.stringForColumn("SONGNAME")  as? String ?? ""
                arrayData1.append(songTitleT!)
                let songLyricsT = results?.stringForColumn("SONGLYRICS")  as? String ?? ""
                arrayData2.append(songLyricsT!)
                let EsongTitleT = results?.stringForColumn("ESONGNAME")  as? String ?? ""


                keerthanaiArray.append(KStruct(SongTitle : songTitleT, SongLyrics : songLyricsT,
                    ESongTitle : EsongTitleT))
            }
        }
    }
}

您可以使用上述方法将默认值设为空字符串。这样您就可以避免fatal error: unexpectedly found nil while unwrapping an Optional value问题。