[英]Remove Item from Struct (Swift)
I have a struct 我有一个结构
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] = [
];
By pressing a UIButton
, an object is added to the struct 通过按UIButton
,对象将添加到结构中
favoriteSongs.append(FavoriteSong(title: songs[thisSong].title, artist: songs[thisSong].artist))
But, I want another UIButton
that removes the object from the struct. 但是,我想要另一个从结构中删除对象的UIButton
。 Something like this: 像这样的东西:
favoriteSongs.remove(FavoriteSong(title: songs[thisSong].title, artist: songs[thisSong].artist))
I'm using a UITableView
to display the information. 我正在使用UITableView
来显示信息。 How would I do this? 我该怎么做?
Find the index
of object and remove it, which matches your song title
and artist
找到对象的index
并将其删除,它与您的歌曲title
和artist
相匹配
let index = favoriteSongs.index{ $0.title == songs[thisSong].title && $0.artist == songs[thisSong].artist}
if let index = index {
favoriteSongs.remove(at: index)
}
struct FavoriteSong : Equatable{
public static func ==(lhs: FavoriteSong, rhs: FavoriteSong) -> Bool {
return lhs.title == rhs.title &&
lhs.artist == rhs.artist
}
}
You have to add extension to Array
to delete object using Equatable
您必须使用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)
}
}
}
And then you can use some thing like this 然后你可以使用这样的东西
favoriteSongs.remove(FavoriteSong(title: songs[thisSong].title, artist: songs[thisSong].artist))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.