我试图在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中工作。我不确定为什么它不再起作用。
答案 0 :(得分:8)
OP提交的错误报告:
已经解决了(修复承诺掌握2017年1月3日),因此不再是即将到来的Swift 3.1中的问题。
这似乎是一个错误(在Swift 2.2中不存在,只有3.0)与以下情况相关:
!
)至少3个术语(使用至少2个基本运算符进行测试,例如+
或-
)。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.在尚未生产的代码版本中报告“错误”,但为了以防万一,您可能应该为此提交雷达。
至于回答你的问题,如何绕过这个问题:
或者,更好的是,使用安全解包您的可选内容,例如使用可选绑定:
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 */
答案 1 :(得分:1)
let q: String? = "Hello"
let w: String? = "World"
let r: String? = "!"
var array = [q, w, r]
print(array.flatMap { $0 }.reduce("", {$0 + $1}))
// HelloWorld!
let q: String? = "Hello"
let w: String? = nil
let r: String? = "!"
var array = [q, w, r]
print(array.flatMap { $0 }.reduce("", {$0 + $1}))
// Hello!
答案 2 :(得分:0)
let val: String? = "nil"
val.flatMap({(str: String) -> String? in
return str + "value"
})
答案 3 :(得分:0)
func getSingleValue(_ value: String?..., seperator: String = " ") -> String? {
return value.reduce("") {
($0) + seperator + ($1 ?? "")
}.trimmingCharacters(in: CharacterSet(charactersIn: seperator) )
}
答案 4 :(得分:0)
var a:String? = "a"
var b:String? = "b"
var c:String? = "c"
var d:String? = ""
let arr = [a,b,c]
arr.compactMap { $0 }.joined(separator: " ")
compactMap用于从展平数组中滤除nil值