user8551563
user8551563

Reputation:

swift: Add value from array

I want to save value in array and check if value in array exist.

I use this code:

to save value

var index = 0
var array = [Int]()

self.array.append(self.index)

But how I can check if value in array exist and show numbers values in array in console?

example:

check value

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell

    if "values for array exist" {

    //show text for all row numbers in the array 
    }

}

save value in array

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    index = indexPath.row
    self.array.append(self.index.row) //save row number

}

Upvotes: 0

Views: 646

Answers (4)

OhadM
OhadM

Reputation: 4803

The Swift way is pretty easy, using index(where:) you can validate your value and if it exist, meaning, index(where:) returned the index you need, remove it.

Code snip:

if let index = array.index(where: { $0 === 1 }) {
    array.remove(at: index)
}

Upvotes: 0

Krishnarjun Banoth
Krishnarjun Banoth

Reputation: 1580

Just change your cellForRowAt tableview delegate method as below.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell

if array.contains(indexPath.row) {

       print("Rows in arrays are \(array)")
  }

}

Upvotes: 0

Saurabh Jain
Saurabh Jain

Reputation: 1698

According to your question you want to find a value exist in array or not so:

Take an example:

let array = ["one","two","three","one"]
var newArray:Array<String> = []

for obj in array {
 if newArray.contains(obj) {
    print(newArray)
}else {
    newArray.append(obj)
}
}

Hope this help you :)

Upvotes: 0

mfaani
mfaani

Reputation: 36287

var index = 0
var array = [String]()

array.append("\(index)")

How to see all that is inside the array

array.forEach({print($0)})

you could also do:

for i in 0..<array.count{
    print(array[i])
}

to check if the array contains:

print(array.contains("5")) // false
print(array.contains("0")) // true

Upvotes: 1

Related Questions