UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 99 question - array lookup

Forums > 100 Days of Swift

I have setup a simple json import to hold my list of words for concentration. Using the simplified technique, I am storying each pair of words as a class :

class Pair: NSObject, Codable {
    var word1: String
    var word2: String

    init(word1: String, word2: String) {
        self.word1 = word1
        self.word2 = word2
    }
}

I am trying to search into an array of Pairs to find the word from the first card and to get it's word2, and then see if that matches the second card, but I am unsure how to do that lookup.

I receive a "Cannot convert value of type 'String?' to expected argument type 'Pair' if I try pairs.firstIndex(of: checkValue)

What is the correct way to search the array of Pairs, I really don't want to brute force it (even thought the number of values is pretty small.

3      

firstIndex(of:) will get you the first index in an array, but that's not really what you want here. What you really want is the first Pair that has a word1 that matches your criteria. So you should be using first(where:) instead...

import Foundation

class Pair: NSObject, Codable {
    var word1: String
    var word2: String

    init(word1: String, word2: String) {
        self.word1 = word1
        self.word2 = word2
    }
}

let pairs = [
    Pair(word1: "kiwi", word2: "grapefruit"),
    Pair(word1: "bread", word2: "butter"),
    Pair(word1: "brick", word2: "mortar"),
    Pair(word1: "leather", word2: "lace"),
    Pair(word1: "mental", word2: "physical"),
]

let checkValue = "leather"
if let firstWord = pairs.first(where: { $0.word1 == checkValue }) {
    print(firstWord.word2)
} else {
    print("not found")
}

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.