Home > OS >  Create a function that will check if data exist in the array
Create a function that will check if data exist in the array

Time:01-27

I am coding a Favorites class that will add, remove, save and load tracks from Soung model. I need another function that will check if track was added to our array or not, but I can't make it work. I have a working example, but it checks only one parameter.

func containsTracks(_ track: Soung) -> Bool {
        tracks.contains(track.name ?? "aboba")
}

I've been trying to create the same thing for Soung, but failed:

func containsTrack(_ song: Soung) -> Bool {
        
        tracks?.contains(where: <#T##(Soung) throws -> Bool#>) // DON'T KNOW WHAT IS THIS
        
 }

So here I am, seeking your help. This function must return true or false in order to create an If statement like that

if containsTrack == true {
    removeTrack()
} else {
    addTrack()
}
class FavoritesNew: ObservableObject {

    @Published var tracks: [Soung]? = []

    init() {
        tracks = loadTracks()
    }

    // MARK: - TRACKS
    

// PROBLEM IS HERE 
    func containsTrack(_ song: Soung) -> Bool {
        
        
        
        return true
        
    }

    
    func addTrack(song: Soung) {
        tracks?.append(song)
        saveTracks()
    }

    func removeTrack(at index: Int) {
        tracks?.remove(at: index)
        saveTracks()
    }

    func saveTracks() {
        if let encoded = try? JSONEncoder().encode(tracks) {
            UserDefaults.standard.set(encoded, forKey: "tracks")
        }
    }

    func loadTracks() -> [Soung] {
        if let encoded = UserDefaults.standard.data(forKey: "tracks") {
            if let decoded = try? JSONDecoder().decode([Soung].self, from: encoded) {
                return decoded
            }
        }

        return []
    }
}

CodePudding user response:

In this code...

tracks?.contains(where: <#T##(Soung) throws -> Bool#>)

The bit that looks like this <#T##(Soung) throws -> Bool#> is an Xcode placeholder. It looks like you have edited it rather than just tapping [Enter] on it to put the value in there.

This is a place holder for a closure (function) that takes a Soung and returns a Bool.

So in your code it should be...

func containsTrack(_ song: Soung) -> Bool {
    tracks.contains { $0.name == song.name }
}

Or even better, is Soung conforms to Equatable...

func containsTrack(_ song: Soung) -> Bool {
    tracks.contains { $0 == song }
}

Or just...

func containsTrack(_ song: Soung) -> Bool {
    tracks.contains(song)
}

And then you don't even need the function at all.

CodePudding user response:

contains(where: takes a closure as a parameter that returns true when a match is found, e.g.

func containsTrack(_ song: Soung) -> Bool {
    tracks.contains(where:  { track in
        song.name == track.name
    })
}
  • Related