【问题标题】:swift: Add value from arrayswift:从数组中添加值
【发布时间】:2017-09-02 11:24:36
【问题描述】:

我想在数组中保存值并检查数组中的值是否存在。

我使用这个代码:

保存价值

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

self.array.append(self.index)

但是如何检查数组中的值是否存在并在控制台中显示数组中的数字值?

示例:

检查值

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 
    }

}

将值保存在数组中

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

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

}

【问题讨论】:

  • “数组中的值 = true”和“显示下一个代码”是什么意思?
  • 谁赞成这个...问题??
  • @Sweeper 我想在数组中添加值。检查数组中的值是否存在。如果数组中的值存在,我应该显示:// my next code .
  • “代码”是什么意思?
  • @MoeAbdul-Hameed 任何代码,例如在控制台中显示数组中的数字值

标签: ios swift


【解决方案1】:
var index = 0
var array = [String]()

array.append("\(index)")

如何查看数组中的所有内容

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

你也可以这样做:

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

检查数组是否包含:

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

【讨论】:

    【解决方案2】:

    根据您的问题,您想查找数组中是否存在值:

    举个例子:

    let array = ["one","two","three","one"]
    var newArray:Array<String> = []
    
    for obj in array {
     if newArray.contains(obj) {
        print(newArray)
    }else {
        newArray.append(obj)
    }
    }
    

    希望对你有帮助:)

    【讨论】:

    • 更新问题
    • @user 使用 contains 方法检查值是否存在
    【解决方案3】:

    只需如下更改您的 cellForRowAt tableview 委托方法。

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

    【讨论】:

    • 有效。但是我可以使用 User.defaults 将值保存在数组中吗?我需要在返回前一个控制器后在单元格中显示文本并在此控制器中返回。如果我回到以前的控制器,我的数组是空的。我使用导航栏在 TableViewController 之间移动。或者有更好的方法来解决这个问题?
    【解决方案4】:

    Swift 方式 非常简单,使用 index(where:) 可以验证您的值,如果存在,则意味着 index(where:) 返回了您需要的索引,将其删除。

    代码片段:

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

    【讨论】:

    • @user,代码片段正是您所需要的,正如您所写 *如果“数组的值存在”* - 这是第一个代码片段所做的。
    • 在数组中我保存行数。在cellForRowAt 中,我应该显示数组中行数的文本。
    • 那么你对代码片段的问题是类型? - 更新答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多