下面是一个示例,展示了如何编写一个带有静态数据的字典类。
class MyDictionary {
static var data: [String: String] = [
"key1": "value1",
"key2": "value2",
"key3": "value3"
]
static func getValue(forKey key: String) -> String? {
return data[key]
}
static func setValue(value: String, forKey key: String) {
data[key] = value
}
}
// 使用示例
MyDictionary.getValue(forKey: "key1") // 输出: "value1"
MyDictionary.setValue(value: "new value", forKey: "key1")
MyDictionary.getValue(forKey: "key1") // 输出: "new value"
在上面的示例中,MyDictionary
类有一个静态属性 data
,它是一个字典类型,用来存储键值对。getValue(forKey:)
方法用于获取指定键的值,setValue(value:forKey:)
方法用于设置指定键的值。
你可以通过调用 MyDictionary.getValue(forKey:)
方法来获取键的值,并使用 MyDictionary.setValue(value:forKey:)
方法来设置键的值。