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

标签 string swift swift3

我正在尝试在 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/

相关文章:

swift - 为什么我的 Playground 在 NSRange() 上崩溃

ios - 在没有 contentSize.height 的情况下获取 UITextView 中的行数

objective-c - 在 Swift 中使用轻量级泛型实现 Objective-C 方法

swift - UIWebView 未在 iOS 10 中加载

java - JAVA将一个字符串分割成3个字符串,每个字符串都有自己的分隔符

java - 如何从字符串中获取特定字符串(子字符串)

javascript - 为什么 JavaScript 有以下几种连线行为?

swift - 为什么扩展不能添加存储属性

json - 'NSInvalidArgumentException',原因 : 'Invalid type in JSON write (_SwiftValue)' with alamofire swift3

c# - 正则表达式匹配不以空格开头、包含或结尾且非空字符串