Swift:类中可选字典的变量:在输出中显示括号

标签 swift dictionary option-type optional-parameters square-bracket

我想在类中创建一个可选的字典变量,这样当我创建一个实例时,我就不必添加该参数...

例子

class Stuff {
     var dictionary: [String: Double]?
     init(dictionary: [String:Double]?=["":0]){
}
}
var instance1    = Stuff(dictionary:["length":1.5])
var array: [Stuff] = [instance1, instance2]

let arraySet = (array[indexPath.row])
let X = arraySet.dictionary!

cell.Label.text = "\(X)"

这有效,但是当我将它分配给 cell.label.text 时,输出显示括号...

“[长度:1.5]”

我怎样才能去掉括号???

最佳答案

去除括号非常复杂,因为必须从字典中提取键/值对:

class Stuff {
  var dictionary: [String: Double]?
  init(dictionary: [String:Double]?=["":0.0]){
    self.dictionary = dictionary
  }
}


 let instance = Stuff(dictionary:["length":1.5])
 if let dict = instance.dictionary where dict.count > 0 {
   let key = dict.keys.first!
   let value = dict[key]!
   label.text = "\(key) : \(value)"
 }

如果您使用非可选文字创建字典,请考虑将变量 dictionary 声明为非可选

关于Swift:类中可选字典的变量:在输出中显示括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33023495/

相关文章:

ios - 如何从 Firestore 返回数组中的数据?

json - 在 Swift 4 中解码复杂的嵌套 JSON 有很多错误

swift - 无法从 XCTest 中的 UIStoryboard 转换自定义 UIViewController

python - 将计数器对象映射到 DataFrame 以创建新列

python - 连接两个字典并处理其共同值(value)

python - 在 Python 中,如何根据键的频率编辑字典中的值?

Java 8 Optional 和 flatMap - 有什么问题吗?

ios - 进度条不会从 for 循环更新

swift 4 : Printing out Bool optionals as either unwrapped true or false or as wrapped nil?

swift - 你能同时进行模式匹配和解包一个包含可选值的元组吗?