Get widget index on Swift

Asked

Viewed 110 times

0

I’m trying to use the method index to know the index of an object within the array but do not know which parameter(s) to pass.

My code:

/// Struct that define the track model 
struct Track {
  let songID: Int
  let songName: String

  init(songID id: Int, songName name: String) {
    songID = id
    songName = name
  }
}

/// Struct that define the playlist model 
struct Playlist {
  var tracks = [Track]()
}

// MARK: - Exemplo
let s = Track(songID: 1, songName: "song1")
let t = Track(songID: 2, songName: "song2")
let u = Track(songID: 2, songName: "song3")
let v = Track(songID: 2, songName: "song4")

var playlist = Playlist.init(tracks: [s, t, u, v])

// se eu passar o objeto t da o seguinte erro: 
// Cannot convert value of type 'Track' to expected argument type '@noescape (Track) throws -> Bool'
if let index = playlist.tracks.indexOf(t){
  print(index)
}

1 answer

3


You have to specify which property you want to compare, as in your example the only property with unique value is the name, I used it to compare.

if let index = playlist.tracks.indexOf({$0.songName == t.songName}){
  print(index)
}

Functional example: http://swiftstub.com/910951409

  • 1

    It was worth it ! At some point I had tried something like this that you showed but it didn’t work, but your answer worked 100%

Browser other questions tagged

You are not signed in. Login or sign up in order to post.