简体   繁体   English

Swift 作为字典值的元组 Swift 5

[英]Swift Tuples as Dictionary Values in Swift 5

I have a Dictionary with a key of type String and values as a tuple:我有一个字典,其键类型为字符串,值作为元组:

var dictionaryTuple = [String: (x: Double, y: Double)]()

How do I set and access the values of the tuple.如何设置和访问元组的值。 This is what I tried这是我试过的

dictionaryTuple["One"].x = 5.5 - compiler gives an error: Value of optional type '(x: Double, y: Double)?' dictionaryTuple["One"].x = 5.5 - 编译器给出错误:可选类型的值'(x: Double, y: Double)?' must be unwrapped to refer to member 'x' of wrapped base type '(x: Double, y: Double)' see playground screenshot below Not sure why the compiler is giving an error.必须解包以引用包装基类型“(x: Double, y: Double)”的成员“x”,请参阅下面的游乐场屏幕截图不确定为什么编译器会出错。 I have not declared the tuple as optional or the dictionary as an optional我没有将元组声明为可选的,也没有将字典声明为可选的在此处输入图像描述

When I change to: dictionaryTuple["One"]?.x = 5.5 - compiler is happy but I am not getting any value back当我更改为: dictionaryTuple["One"]?.x = 5.5 - 编译器很高兴,但我没有得到任何回报在此处输入图像描述

If I change it to: dictionaryTuple["One"]..x = 5.5 - it crashes.如果我将其更改为: dictionaryTuple["One"]..x = 5.5 - 它会崩溃。 在此处输入图像描述

What am I doing wrong?我究竟做错了什么? Do I need to initialize the tuple before using it?我需要在使用元组之前对其进行初始化吗? if so how?如果是这样怎么办?

Thanks very much!非常感谢!

Why not construct your struct like this?为什么不这样构造你的结构?

struct DT {
    let key: String
    let x: Double
    let y: Double
}

let dt = DT(key: "One", x: 1, y: 2)

If you really want your own way, same as in your question:如果你真的想要自己的方式,就像你的问题一样:

struct DT {
    var dictionaryTuple = [String: (x: Double, y: Double)]()
}


var dt = DT(dictionaryTuple: ["One": (x: 1, y: 2)])

print(dt)//prints -> DT(dictionaryTuple: ["One": (x: 1.0, y: 2.0)])

var tuple: (x: Double, y: Double) = dt.dictionaryTuple["One"]!
tuple.x = 100
tuple.y = 200

//apply
dt.dictionaryTuple["One"] = tuple

print(dt)//prints -> DT(dictionaryTuple: ["One": (x: 100.0, y: 200.0)])

the key here is that I explicitly declary the type of the tuple variable, and cast it.这里的关键是我显式声明tuple变量的类型,并将其强制转换。

You can insert either a tuple like this您可以插入这样的元组

dictionaryTuple["One"] = (3.3, 4.4)

or update an existing one but then you need to treat it as an optional.或更新现有的,但您需要将其视为可选的。

dictionaryTuple["Two"]?.x = 5.5

or supply a default value when updating.或在更新时提供默认值。

dictionaryTuple["Three", default: (0.0, 0.0)].x = 5.5

Performing these 3 operations will mean the dictionary contains 2 tuples执行这 3 个操作将意味着字典包含 2 个元组

var dictionaryTuple = [String: (x: Double, y: Double)]()
dictionaryTuple["One"] = (3.3, 4.4)
dictionaryTuple["Two"]?.x = 5.5
dictionaryTuple["Three", default: (0.0, 0.0)].x = 5.5
print(dictionaryTuple)

["Three": (x: 5.5, y: 0.0), "One": (x: 3.3, y: 4.4)] [“三”:(x:5.5,y:0.0),“一”:(x:3.3,y:4.4)]

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

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