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

时间:2017-04-19 16:52:55

标签: swift macos cocoa

我希望下面的代码和评论说明我正在努力学习如何做。

访问名为iphone的Struct属性,我可以,它有效:

ERROR in ch.qos.logback.classic.joran.action.InsertFromJNDIAction - [java:comp/env/applicationName] has null or empty value

访问名为iphone的Struct属性,我不能并且想要使用包含字符串值“iPhone”的变量来访问它:

IconSizes().iphone

在更多背景下:

IconSizes().selectedIconType

结构:

selectedIconType = "iphone" // already set as String

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

1 个答案:

答案 0 :(得分:0)

在运行时引用变量的名称就像它们是字符串一样,在解释语言中通常很容易,而在移动到编译的静态语言时则更少。明确可能会更好。

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