【问题标题】:Cannot convert value of type 'String?' to expected element type 'Array<String>.ArrayLiteralElement' (aka 'String')无法转换“字符串”类型的值?到预期的元素类型'Array<String>.ArrayLiteralElement'(又名'String')
【发布时间】:2022-01-13 14:44:48
【问题描述】:

我的 firebase 文档中的一个字段是一个包含用户 ID 的字符串数组。

当我尝试在我的一个视图中初始化它时,我得到了错误 Cannot convert value of type 'String?' to expected element type 'Array&lt;String&gt;.ArrayLiteralElement' (aka 'String')

这就是我正在做的事情

@State var playerIds: [String] = [Auth.auth().currentUser?.uid, "SomeRandomHardcodedUserID"]

下面这行有效,但上面提到的那一行无效。

@State var playerIds: [String] = ["SomeHardcodedUID", "SomeOtherHardcodedUserID"]

我的意图是使用playerIds 构造一个可编码的对象以发送到 Firestore。 下面的行适用于硬编码的 userId。

let newGame = Game(gameTime: gameTime, playerIds: playerIds, inProgress: gameInProgress, winnerId: winnerId)

将当前用户的 userId 放入我的数组中的正确方法是什么?

【问题讨论】:

  • Auth.auth().currentUser?.uid :这是一个String?,即可选,所以它可以是nil。但是您将playerIds 声明为[String],因此它不能包含可选值。
  • 确实如此。我刚刚想通了,我也发布了一个答案。谢谢!

标签: swift google-cloud-firestore swiftui firebase-authentication


【解决方案1】:

所以我发现解决方法是将数组类型定义为[String?] 而不是[String],这解决了我的问题。 通过将playerIdsGame 结构模型更改为也使用[String?] 而不是[String],修复了将playerIds 作为参数传递的问题

【讨论】:

  • [String?] 是一个非常糟糕的选择。您将如何处理丢失/未授权的用户 ID?
  • 它可能是。我正在努力改进代码库以尽快摆脱这些东西。计划仅将其用作临时解决方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-02
  • 1970-01-01
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多