我有一个结构体
struct FavoriteSong {
var title: String
var artist: String
init(title : String, artist : String) {
self.title = title
self.artist = artist
}
init?(dictionary : [String:String]) {
guard let title = dictionary["title"],
let artist = dictionary["artist"] else { return nil }
self.init(title: title, artist: artist)
}
var propertyListRepresentation : [String:String] {
return ["title" : title, "artist" : artist]
}
}
var favoriteSongs: [FavoriteSong] = [
];通过按UIButton,可将对象添加到结构中
favoriteSongs.append(FavoriteSong(title: songs[thisSong].title, artist: songs[thisSong].artist))但是,我想要另一个从结构中删除对象的UIButton。如下所示:
favoriteSongs.remove(FavoriteSong(title: songs[thisSong].title, artist: songs[thisSong].artist))我正在使用UITableView来显示信息。我该怎么做呢?
发布于 2017-07-03 20:40:23
找到object的index并将其移除,该your与您的歌曲title和artist匹配
let index = favoriteSongs.index{ $0.title == songs[thisSong].title && $0.artist == songs[thisSong].artist}
if let index = index {
favoriteSongs.remove(at: index)
}发布于 2017-07-03 20:44:06
struct FavoriteSong : Equatable{
public static func ==(lhs: FavoriteSong, rhs: FavoriteSong) -> Bool {
return lhs.title == rhs.title &&
lhs.artist == rhs.artist
}
}要使用Equatable删除对象,必须向Array添加扩展
extension Array where Element: Equatable {
// Remove first collection element that is equal to the given `object`:
mutating func remove(object: Element) {
if let index = index(of: object) {
remove(at: index)
}
}
}然后你可以用一些像这样的东西
favoriteSongs.remove(FavoriteSong(title: songs[thisSong].title, artist: songs[thisSong].artist))https://stackoverflow.com/questions/44885581
复制相似问题