繁体   English   中英

Swift 作为字典值的元组 Swift 5

[英]Swift Tuples as Dictionary Values in Swift 5

我有一个字典,其键类型为字符串,值作为元组:

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

如何设置和访问元组的值。 这是我试过的

dictionaryTuple["One"].x = 5.5 - 编译器给出错误:可选类型的值'(x: Double, y: Double)?' 必须解包以引用包装基类型“(x: Double, y: Double)”的成员“x”,请参阅下面的游乐场屏幕截图不确定为什么编译器会出错。 我没有将元组声明为可选的,也没有将字典声明为可选的在此处输入图像描述

当我更改为: dictionaryTuple["One"]?.x = 5.5 - 编译器很高兴,但我没有得到任何回报在此处输入图像描述

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

我究竟做错了什么? 我需要在使用元组之前对其进行初始化吗? 如果是这样怎么办?

非常感谢!

为什么不这样构造你的结构?

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

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

如果你真的想要自己的方式,就像你的问题一样:

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)])

这里的关键是我显式声明tuple变量的类型,并将其强制转换。

您可以插入这样的元组

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

或更新现有的,但您需要将其视为可选的。

dictionaryTuple["Two"]?.x = 5.5

或在更新时提供默认值。

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

执行这 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)

[“三”:(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