gpt4 book ai didi

string - 如何在 swift 3.0 中连接多个可选字符串?

转载 作者:行者123 更新时间:2023-11-28 08:26:35 24 4
gpt4 key购买 nike

我正在尝试在 swift 3 中连接多个字符串:

var a:String? = "a"
var b:String? = "b"
var c:String? = "c"
var d:String? = a! + b! + c!

编译时出现以下错误:

error: cannot convert value of type 'String' to specified type 'String?'
var d:String? = a! + b! + c!
~~~~~~~~^~~~

这曾经在 swift 2 中工作。我不确定为什么它不再工作了。

最佳答案

OP 提交的错误报告:

已解决(已提交 master 2017 年 1 月 3 日修复),因此在即将推出的 Swift 3.1 中应该不再是问题。


这似乎是一个错误(在 Swift 2.2 中不存在,仅在 3.0 中存在)与以下情况相关:

  • 对表达式中的至少 3 个术语使用强制展开运算符 (!)(使用至少 2 个基本运算符测试,例如 +-).
  • 出于某种原因,考虑到上述情况,Swift 搞乱了表达式的类型推断(具体来说,对于表达式中的 x! 术语本身)。

对于下面的所有例子,让:

let a: String? = "a"
let b: String? = "b"
let c: String? = "c"

存在错误:

// example 1
a! + b! + c!
/* error: ambiguous reference to member '+' */

// example 2
var d: String = a! + b! + c!
/* error: ambiguous reference to member '+' */

// example 3
var d: String? = a! + b! + c!
/* error: cannot convert value of type 'String'
to specified type 'String?' */

// example 4
var d: String?
d = a! + b! + c!
/* error: cannot assign value of type 'String'
to specified type 'String?' */

// example 5 (not just for type String and '+' operator)
let a: Int? = 1
let b: Int? = 2
let c: Int? = 3
var d: Int? = a! + b! + c!
/* error: cannot convert value of type 'Int'
to specified type 'Int?' */
var e: Int? = a! - b! - c! // same error

错误不存在:

/* example 1 */
var d: String? = a! + b!

/* example 2 */
let aa = a!
let bb = b!
let cc = c!
var d: String? = aa + bb + cc
var e: String = aa + bb + cc

/* example 3 */
var d: String? = String(a!) + String(b!) + String(c!)

然而,由于这是 Swift 3.0-dev,我不确定这是否真的是一个“错误”,以及政策 w.r.t.在尚未生产的代码版本中报告“错误”,但您可能应该为此提交雷达,以防万一。

至于回答您关于如何规避此问题的问题:

  • 使用例如Bug not present: Example 2 上面的中间变量,
  • 或者明确告诉 Swift 3 项表达式中的所有项都是字符串,如上面的错误不存在:示例 3
  • 或者,更好的是,使用安全展开您的可选项目,例如使用可选绑定(bind):

    var d: String? = nil
    if let a = a, b = b, c = c {
    d = a + b + c
    } /* if any of a, b or c are 'nil', d will remain as 'nil';
    otherwise, the concenation of their unwrapped values */

关于string - 如何在 swift 3.0 中连接多个可选字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39812216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com