简体   繁体   English

如何使用与String Swift同名的变量

[英]How to use variable with the same name as String Swift

I am trying to optimize my code. 我正在尝试优化我的代码。 I want to do the following: if I have an element in the dictionary dict that is in firstNames array I want to write this element directly to the first variable, same with second and etc. Here my code example. 我要执行以下操作:如果字典字典dict中有一个位于firstNames数组中的firstNames我想将此元素直接写入first变量,与second相同,等等。这是我的代码示例。 I've created names array that contains linked variables firstNames <-> first , secondNames <-> second and etc. Also I am trying to iterate through the loop and to set values to first , second and etc. using val 我创建了包含链接变量firstNames <-> firstsecondNames <-> second等的names数组。另外,我尝试遍历循环并将值设置为firstsecond等,使用val

    let dict = ["type": "1", "word": "abc"] // this is example
    let firstNames = ["1", "2"]
    let secondNames = ["3", "4"]
    var first = String()
    var second = String()
    let names = [firstNames: first, secondNames: second]
    for el in dict {
        for var (key, val) in names {
            if (key as! [String]).contains(el["type"]!) {
                if ((val as! String) != "") {
                    val = (val as! String) + ", " + el["word"]!
                }
                else {
                    val = el["word"]!
                }
            }
        }
    }

This code doesn't have any runtime errors. 此代码没有任何运行时错误。 But unfortunately when I am trying to set val in the loop nothing is happening. 但是不幸的是,当我尝试在循环中设置val时,没有任何反应。 What I am doing wrong or may be there is a more elegant solution? 我做错了还是有更好的解决方案?

Thanks for any help. 谢谢你的帮助。

Swift is a compiled, mostly static language, and the optimizer is free to have removed these temporary variables entirely if they aren't needed. Swift是一种编译后的,主要是静态的语言,优化器可以自由地完全删除这些临时变量(如果不需要)。 The names of local variables aren't available at runtime. 局部变量的名称在运行时不可用。 This approach won't work. 这种方法行不通。 It could work if you used a dictionary to hold "first" and "second" as string keys (which is where Paulw11 is pointing you), but this is the wrong approach in Swift. 如果您使用字典将“第一”和“第二”作为字符串键(Paulw11指向您的位置),这可能会起作用,但这在Swift中是错误的方法。

Let's start with dict. 让我们从字典开始。 This is not a proper use of a Dictionary. 这不是对字典的正确使用。 This is not a arbitrary mapping of strings to strings. 这不是字符串到字符串的任意映射。 It is a mapping of specific field identifiers to values. 它是特定字段标识符到值的映射。 That's the definition of a struct. 那就是结构的定义。

It is possible that "type" really is "an arbitrary integer," but I strongly suspect that it is actually "a value from a constrained list of values." “类型”确实有可能是“任意整数”,但我强烈怀疑它实际上是“受约束的值列表中的值”。 That's a enum. 那是一个枚举。

If we put those together, dict is really Element: 如果我们将它们放在一起,那么dict实际上就是Element:

enum ElementType {
    case one
    case two
    case three
    case four
}

struct Element {
    let type: ElementType
    let word: String
}

And your name selectors are arbitrary lists of ElementTypes: 您的名称选择器是ElementTypes的任意列表:

let firstNameTypes = [ElementType.one, .two]
let secondNameTypes = [ElementType.three, .four]

Then, rather than just one dict, we can imagine lists of elements (which I assume you actually have outside this loop). 然后,我们可以想象元素列表(而不是一个字典)(我假设您实际上在此循环之外)。

let elements = [
    Element(type: .one, word: "abc"),
    Element(type: .two, word: "bcd"),
    Element(type: .three, word: "efg"),
    Element(type: .four, word: "fgh"),
]

And now our loop is trivial and clearly says what it means. 现在,我们的循环变得微不足道了,并且清楚地说明了这意味着什么。

let firstNames = elements.filter { firstNameTypes.contains($0.type) }
let secondNames = elements.filter { secondNameTypes.contains($0.type) }

And to get our final string is also trivial: 并获得我们的最终字符串也很简单:

let firstString = firstNames.map { $0.word }.joined(separator: ",")
let secondString = secondNames.map { $0.word }.joined(separator: ",")

While this code is very clear, it does iterate over the elements twice and over the "NameTypes" lists once for each element. 尽管这段代码很清楚,但是它对元素进行了两次迭代,并对每个元素对“ NameTypes”列表进行了一次迭代。 In the vast majority of cases, that's fine. 在大多数情况下,这很好。 It's what computers do, But if you have many thousands of elements (and especially if the name filtering lists were long), it could be expensive and we could write a function that returned a dictionary of result strings (by rewriting filter by hand). 这是计算机的工作,但是,如果您有成千上万的元素(尤其是名称过滤列表很长),则可能会很昂贵,我们可以编写一个返回结果字符串字典的函数(通过手动重写filter )。 If that's your problem, I can write that up (if you'll explain the underlying problem more clearly), but in most cases for modest sized lists, this is the best approach. 如果那是您的问题,我可以写下来(如果您能更清楚地说明潜在问题),但是在大多数情况下,对于中等大小的列表,这是最好的方法。

My guess is that 'val' is temporary variable and can't be assign to so that it would affect the 'dict' dictionary. 我的猜测是'val'是临时变量,不能分配给它,这样会影响'dict'字典。

Instead of 代替

val = ..

try using 尝试使用

dict[key] = ... 

Also, it would be great if you would describe what you are trying to achieve with you code. 另外,如果您要描述使用代码实现的目标,那就太好了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM