>') 到 (又名'字典'),javascript,swift,dictionary"/>

首页 > 解决方案 > 无法分配类型的值(又名“数组”>') 到 (又名'字典')

问题描述

这是我的代码:

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),
    });
  }

标签: javascriptswiftdictionary

解决方案


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

objectNode.stylesMap = stylesArray

和:

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

推荐阅读