raaamonnn
raaamonnn

Reputation: 25

Why am I getting this error using firstIndex(where:

I have an array of class type "Word" and am trying to grab the right "Word" out of the array based on the I am trying to achieve this by using Words.words.firstIndex(where: {$0.id == wordId}). But I am getting this error: Cannot convert value of type 'Array<Word>.Index?' (aka 'Optional<Int>') to expected argument type 'Word'

Thanks!

Code:

    var randomIds:[Int] = []
    
    for _ in 1 ... 4 {
        
        //to make sure there aren't duplicates
        var wordId:Int = Int.random(in: 0..<Words.words.count)
        while randomIds.contains(wordId){
            wordId = Int.random(in: 0..<Words.words.count)
        }
        randomIds.append(wordId)
        
        
        
        answers.append(Answer(id: wordId, isChosen: false, isAnswer: false, word: Words.words.firstIndex(where: {$0.id == wordId})))
    }

"Words" Class:

class Words{

    static var words:[Word] = [Word(id: 0, EnglishWord: "Hello", DariWord: "Salaam"),Word(id: 1, EnglishWord: "Bread", DariWord: "Naan"),Word(id: 2, EnglishWord: "Thank You", DariWord: "Tashakor"),Word(id: 3, EnglishWord: "Yes", DariWord: "Baleh"), Word(id: 4, EnglishWord: "a", DariWord: "a"), Word(id: 5, EnglishWord: "b", DariWord: "b"), Word(id:6, EnglishWord: "c", DariWord: "c"), Word(id: 7, EnglishWord: "d", DariWord: "d")]

}

struct Word: Codable, Identifiable{

    var id: Int
    var EnglishWord:String
    var DariWord:String
    
    init(id: Int, EnglishWord: String, DariWord:String)
    {
        self.id = id
        self.EnglishWord = EnglishWord
        self.DariWord = DariWord
    }
    //Do Json Stuff (Decoding/Encoding)
}

Upvotes: 0

Views: 112

Answers (1)

vadian
vadian

Reputation: 285072

Please read your code and the error message carefully. The error is pretty obvious:

You are grabbing the index of the word in the array, not the word itself. Delete Index

Words.words.first(where: {$0.id == wordId})

Upvotes: 4

Related Questions