【问题标题】:Cannot assign value of type (aka 'Array<Dictionary<String, Style>>') to (aka 'Dictionary<String, Style>')无法将类型 (aka 'Array<Dictionary<String, Style>>') 的值分配给 (aka 'Dictionary<String, Style>')
【发布时间】:2021-11-10 22:01:58
【问题描述】:

这是我的代码:

override func style(node: Node) throws -> StyleNode {
    guard let objectNode = try super.style(node: node) as? StyleNode
    else {
      throw UEErrors.unrecoverableError(message: "Could not create Node")
    }

    guard let stylesArray = node.stylesMap else {
      throw UEErrors.unrecoverableError(message: "stylesMap is missing")
    }
    objectNode.stylesMap = stylesArray //error : Cannot assign value of type '[[StyleID : Style]]' (aka 'Array<Dictionary<String, Style>>') to type '[StyleID : Style]' (aka 'Dictionary<String, Style>')
    return objectNode
  }

注意:var stylesMap: [[StyleID: Style]]? 如何创建stylesArray 的字典? (我认为 javascript 中的 Map 是 swift 中的字典)

我正在尝试将 javascript 代码移植到 swift 中。下面是javascript代码:

static style(
    node: Node,
    baseProps: BaseConstructorProperties,
  ): this {
    const stylesArray = assertNonNull(
      Node?.stylesMap,
      'stylesMap is missing',
    );

    return new this({
      ...baseProps,
      stylesMap: new Map(stylesArray),
    });
  }

【问题讨论】:

  • 您当前有一个 [StyleID : Style] 数组,您正尝试将其设置为接受该类型的单个值的属性。大概,你需要决定你想要哪个项目。第一个?
  • @jnpdx 是的第一个

标签: javascript swift dictionary


【解决方案1】:

如果您只想要第一项,如 cmets 中所述,您可以替换以下行:

objectNode.stylesMap = stylesArray

与:

guard let first = stylesArray.first else {
  throw UEErrors.unrecoverableError(message: "No items")
}
objectNode.stylesMap = first

【讨论】:

  • 如果我想返回第二个,我应该使用 stylesArray.last?
  • 如果它只有两个项目,是的。或者stylesArray[1](确保首先检查你没有超出数组的长度——如果超出数组长度,通过下标访问会崩溃)
  • 如果我想返回一个字典怎么办?
  • [StyleID : Style] 字典
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多