【问题标题】:Swift: How do I print out the value of a dictionary key inside a string expression? [duplicate]Swift:如何在字符串表达式中打印出字典键的值? [复制]
【发布时间】:2014-06-17 13:24:27
【问题描述】:

由于某种原因,我无法使这个表达式起作用:

let expandedBio: Dictionary<String,AnyObject> = ["name":"Saurabh", "profession":"developer", "language":"java", "employed": true]

if let employed : AnyObject = expandedBio["employed"] {
    println("\(expandedBio[\"name\"]) is not available")
}

如何输出println 语句?我得到了错误

Unexpected "" character  error in string interpolation

我该怎么做?

【问题讨论】:

  • 这个问题在swift 2.1中解决了

标签: dictionary swift


【解决方案1】:

在当前版本的 Swift 中,您必须先将值放入它自己的常量/变量中,然后再使用它。

if let employed : AnyObject = expandedBio["employed"] {
    let t = expandedBio["name"]
    println("\(t) is not available")
}

【讨论】:

  • 我不得不使用let t : AnyObject? = expandedBio["name"]
  • 不一定,但为了更好的可读性建议。
  • 虽然“如果让受雇”已经预计“受雇”可能为零(因此可以处理这种情况),但“t”的简单赋值可能会导致一个 nil 值 -> “因为可以请求不存在值的键,字典的下标返回字典值类型的可选值。” -> 因此,您应该通过将 t 定义为 "AnyObject?" 来明确该选项
  • 这个问题在swift 2.1中解决了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多