swift - 仅字典存储一个键和值/覆盖上一个键和值

标签 swift dictionary memory logic

我目前正在使用字典来存储每个 TableView 单元格中分段控件的索引值。每个分段控件都有一个与其所在行的索引路径相对应的标记。

在字典中,键是分段控件的标签(或者分段控件所在行的索引路径,无论你喜欢什么),值是分段控件本身的索引(即选项0对应到索引 0,选项 1 对应于索引 1)。

因此,如果有三行,并且第一个分段控件选择了选项 0,第二个分段控件选择了选项 1,第三个分段控件选择了选项 1,则字典将如下所示:

[0:0, 1:1, 2:1]

但是,这不是我得到的。当我打印字典时,其中唯一的值是我刚刚按下的按钮的键和索引。像这样的事情:

 [0:0]
 [1:1]
 [2:1]

如果我按顺序为分段控件 1 选择选项 0、为分段控件 2 选择选项 1、为分段控件 3 选择选项 1。

这是我的引用代码:

import UIKit

class MyTableViewController: UITableViewController {

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 150
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return 3
}

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


    let nameLabel: UILabel = {
        let label = UILabel()
        label.text = "Sample Item"
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let actionButton = YSSegmentedControl(
        frame: CGRect.zero,
        titles: [
            "Yes",
            "No"
        ])


actionButton.delegate = self
cell.addSubview(nameLabel)
cell.addSubview(actionButton)
actionButton.translatesAutoresizingMaskIntoConstraints = false

cell.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]-160-[v1]-16-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel, "v1": actionButton]));
cell.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
cell.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-60-[v0]-60-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": actionButton]))

actionButton.tag = indexPath.row


    cell.backgroundColor = .green
    return cell

}

override func viewDidLoad() {
    super.viewDidLoad()



    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellId")

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

extension MyTableViewController: YSSegmentedControlDelegate {
func segmentedControl(_ segmentedControl: YSSegmentedControl, willPressItemAt     index: Int) {
    var indexToTag = [Int:Int]()
    indexToTag[index] = segmentedControl.tag

    // Looking up tag
    let tag = indexToTag[index]

    print("\(indexToTag)")

}

func segmentedControl(_ segmentedControl: YSSegmentedControl, didPressItemAt index: Int) {

}

}

以及我的应用程序的图片:

/image/ezMUJ.png

谢谢, 尼克

最佳答案

修订:在我看来,你每次之前都会得到一本新字典

indexToTag[index] = segmentedControl.tag 

代码示例使用变量indexToTag,其作用域是函数本地的,并且不会保留。

如果可以从函数内部移动字典 (indexToTag), 但仍在扩展中,则可以记住实例的存储属性。

问题是 swift 扩展不直接允许在扩展中存储属性。 (检查 Stack Overflow 中的条目以获取存储的属性和 swift 扩展)。

挑战在于让您的代码具有所需的类或实例变量来记住字典内容。

这是一个使用简单扩展的沙箱示例。字典位于扩展程序之外。

我不知道你的代码如何最好地完成类似的事情。

import Foundation

var indexToTag = [Int:Int]()

extension String {
   func control( index: Int, scTag: Int) {
      indexToTag[index] = scTag

      let tag = indexToTag[index]!
      print(" tag is \(tag)    indexToTag  contains: \(indexToTag)")
   }
}

let bst = String()

bst.control(index: 0, scTag: 0)
bst.control(index: 1, scTag: 1)
bst.control(index: 2, scTag: 1)

打印内容

 tag is 0    indexToTag  contains: [0: 0]
 tag is 1    indexToTag  contains: [0: 0, 1: 1]
 tag is 1    indexToTag  contains: [2: 1, 0: 0, 1: 1]

请注意,indexToTag 是一个字典,因此内容不具有原始插入顺序。

关于swift - 仅字典存储一个键和值/覆盖上一个键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44425439/

相关文章:

ios - 在 Swift 中将字典对象传递给 Objective C 协议(protocol)

python - 从列表字典中过滤元素

linux - 什么是私有(private)页面?

swift - 使用协议(protocol)扩展符合协议(protocol)的结构

properties - Swift 类 : Property not initialized at super. init 调用中出现错误

javascript - 如何通过双击将一个词作为网页的输入?

C结构和内存分配

python - Numpy 内存不足

swift - 是否可以从 SwiftUI 使用 ASWebAuthenticationSession ?

ios - 使用 UIView Transition 滑动动画?