gpt4 book ai didi

swift - 初始化 Struct 实例后使用 String 变量获取 Struct 属性

转载 作者:行者123 更新时间:2023-11-30 12:31:28 25 4
gpt4 key购买 nike

我希望下面的代码和注释能够说明我正在尝试学习如何做。

访问名为 iphone 的结构属性,我可以,它的有效范围为:

IconSizes().iphone

访问名为 iphone 的结构属性,我不能但希望使用包含字符串值“iPhone”的变量来访问它:

IconSizes().selectedIconType

更多上下文:

selectedIconType = "iphone" // already set as String

let sizesNamesArray = IconSizes().selectedIconType // obviously raises error.

结构:

struct IconSizes {
var typesList: Array<String>

var iphone: [Dictionary<String, Any>]

init() {
self.typesList = ["iPhone"]

self.iphone = [
["size":16,"name":"icon_small.png"],
["size":32,"name":"icon_small@2x.png"],
["size":32,"name":"icon_medium.png"],
["size":64,"name":"icon_medium@2x.png"],
["size":64,"name":"icon_large.png"],
["size":128,"name":"icon_large@2x.png"],
["size":128,"name":"icon.png"],
["size":256,"name":"icon@2x.png"]
]
}
}

最佳答案

在解释语言中,在运行时引用变量名称就像它们是字符串一样通常很容易,但当您转向编译的静态语言时,就不那么容易了。明确表达可能会效果更好。

struct IconSizes {
var typesList: Array<String>

var iphone: [Dictionary<String, Any>]
var types = [String : [Dictionary<String, Any>]]()

init() {
self.typesList = ["iPhone"]

self.iphone = [
["size":16,"name":"icon_small.png"],
["size":32,"name":"icon_small@2x.png"],
["size":32,"name":"icon_medium.png"],
["size":64,"name":"icon_medium@2x.png"],
["size":64,"name":"icon_large.png"],
["size":128,"name":"icon_large@2x.png"],
["size":128,"name":"icon.png"],
["size":256,"name":"icon@2x.png"]
]
self.types["iPhone"] = self.iphone
}
}

let selectedIconType = "iPhone"
print(IconSizes().types[selectedIconType])

关于swift - 初始化 Struct 实例后使用 String 变量获取 Struct 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43501707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com