2017-07-03 45 views
0

我有一个结构从结构(SWIFT)

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来显示信息。我将如何做到这一点?

+0

删除哪个元素?你没有提到应用程序扩展时它将如何工作。你为一个结构解释了它的例子,但是你想要移除哪个元素。你有这些集合视图或tableview吗?添加更多细节! –

+0

正如你将喜欢的歌曲存储在一个'Array'中。所以你必须记住存储歌曲的'index',然后你可以通过索引来删除它。其他选项是通过'title'将它存储在'Dictionary'中,然后你可以通过'title'键删除fvrt歌曲。 –

+1

你可以使'FavoriteSong'符合'Equatable'协议,然后遍历数组以找到使用== ==操作符的歌曲的潜在索引,如果找到了,将它从数组中移除。 – Sajjon

回答

0

查找对象的index并删除它,你的歌titleartist

let index = favoriteSongs.index{ $0.title == songs[thisSong].title && $0.artist == songs[thisSong].artist} 
if let index = index { 
    favoriteSongs.remove(at: index) 
} 
0
struct FavoriteSong : Equatable{ 

public static func ==(lhs: FavoriteSong, rhs: FavoriteSong) -> Bool { 
    return lhs.title == rhs.title && 
      lhs.artist == rhs.artist 
    } 
} 

匹配,就必须扩展添加到Array使用删除对象Equatable

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))