Reputation: 1178
I'm working in a project in Swift 3.0 and I have a loop that would give me the state of an object (gives a boolean value in a an array sequence). My requirement is if the element state is "true" I wants to get the relevant index path of that, so using that indexPath
I can get the whole object from my original array. So inside a loop how can i get that as well? My partially done code is below. In a comment I have stated where I wants to pass this indexPath
.
func tapFunction(sender: UIButton) {
// This gives me the selected indexPath
print("ID :",sender.accessibilityIdentifier!)
if let rowIndexString = sender.accessibilityIdentifier, let rowIndex = Int(rowIndexString) {
self.sateOfNewSongArray[rowIndex] = !self.sateOfNewSongArray[rowIndex]
}
sender.isSelected = !sender.isSelected
for (element) in self.sateOfNewSongArray {
//This is where I wants to pass the rowIndex that became true
if element == true {
selectedSongList.addingObjects(from: [songList[rowIndex]])
}
}
}
Upvotes: 4
Views: 1764
Reputation: 79656
Note: Make sure your array 'sateOfNewSongArray' has boolean types of elements
Try following solutions:
Sample Code 1: According to your current code in your question.
func tapFunction(sender: UIButton) {
// This gives me the selected indexPath
print("ID :",sender.accessibilityIdentifier!)
if let rowIndexString = sender.accessibilityIdentifier, let rowIndex = Int(rowIndexString) {
self.sateOfNewSongArray[rowIndex] = !self.sateOfNewSongArray[rowIndex]
}
sender.isSelected = !sender.isSelected
for (index, element) in self.sateOfNewSongArray.enumerated() {
if element {
if let songName:String = songList[index] {
selectedSongList.append(songName)
}
}
}
}
Sample Code 2: More easier and concise.
func tapFunction(sender: UIButton) {
// This gives me the selected indexPath
print("ID :",sender.accessibilityIdentifier!)
if let rowIndexString = sender.accessibilityIdentifier, let rowIndex = Int(rowIndexString) {
if let songName:String = songList[rowIndex] {
selectedSongList.append(songName)
}
}
}
enumerated()
is a function, returns sequence of pairs enumerating with index and element of array (by iterating elements of array)
Here is basic sample code, for your understanding. Copy and execute this code:
let songList = [“cat”, “dog”, “elephant”]
let sateOfNewSongArray = [false, true, false]
let selectedSongList = [String]()
for (index, element) in self.sateOfNewSongArray.enumerated() {
if element {
if let animalName:String = songList[index] {
selectedSongList.append(animalName)
}
}
}
print(“selectedSongList - \(selectedSongList)”)
Upvotes: 1