简体   繁体   English

二元运算符“+”不能应用于“字符串”和“字符串?”类型的操作数

[英]Binary operator '+' cannot be applied to operands of type 'String' and 'String?'

new to programming and not quite grasping how this is wrong, any advice is appreciated.编程新手,不太了解这是怎么回事,任何建议都值得赞赏。

func exercise() {
    let alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

    var char0 = alphabet.randomElement()
    var char1 = alphabet.randomElement()
    var char2 = alphabet.randomElement()
    var char3 = alphabet.randomElement()
    var char4 = alphabet.randomElement()
    var char5 = alphabet.randomElement()

    print(char0 + char1 + char2 + char3 + char4 + char5)
}

The important part of the error message to understand is that String and String?要理解的错误消息的重要部分是 String 和 String? (optional) are considered to be 2 different types by the compiler. (可选)被编译器认为是 2 种不同的类型。

For some cases the compiler can make a (implicit) conversion so the types are the same but not here since it can't convert nil and the + operator only works for two variables/literal values of the same type.在某些情况下,编译器可以进行(隐式)转换,因此类型相同但此处不一样,因为它无法转换 nil 并且 + 运算符仅适用于相同类型的两个变量/文字值。

Consider this case考虑这种情况

var char0 = alphabet.randomElement()
var char1 = alphabet.randomElement() ?? ""

If we now do print("0: \(char0) 1: \(char1)") the result is quite different for the 2 variables如果我们现在做print("0: \(char0) 1: \(char1)")两个变量的结果是完全不同的

0: Optional("p") 1: d 0:可选(“p”)1:d

which we also see if we examin their types using print("0: \(type(of: char0)) 1: \(type(of: char1))")如果我们使用print("0: \(type(of: char0)) 1: \(type(of: char1))")检查他们的类型,我们也会看到

0: Optional<String> 1: String 0:可选<字符串> 1:字符串

Others have explained why your code gives an error.其他人已经解释了为什么您的代码会出错。 ( String.randomElement() returns an Optional<String> , which is not the same thing as a String, and you can't use + to concatenate Optionals.) String.randomElement()返回一个Optional<String> ,这与 String 不同,您不能使用 + 连接 Optional。)

Another point: Your code is verbose and repetitive.另一点:您的代码冗长且重复。 There is a principle, "DRY", in computer science.计算机科学中有一个原则“DRY”。 It stands for "Don't Repeat Yourself".它代表“不要重复自己”。 Any time where you have the same code over and over (maybe with slight variations) it is "code smell", and an opportunity to improve.任何时候,如果您一遍又一遍地使用相同的代码(可能会有细微的变化),这就是“代码异味”,也是改进的机会。

You could rewrite your code without repetition like this:你可以像这样重写你的代码而不重复:

func exercise() {
    let alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

   var result = ""
   for _ in 1...6 {
     result.append(alphabet.randomElement() ?? "")
   }
   print(result)
}

In that version, the expression alphabet.randomElement() only appears once.在那个版本中,表达式alphabet.randomElement()只出现一次。 You don't repeat yourself.你不要重复自己。 It also uses the ??它还使用?? "nil coalescing operator" to convert possibly nil results to blank strings. “nil 合并运算符”将可能的 nil 结果转换为空白字符串。


Another way to handle it would be to define an override of the += operator that lets you append String optionals to a string:处理它的另一种方法是定义+=运算符的覆盖,它允许您将 append 字符串选项转换为字符串:

public func +=(left: inout String, right: Optional<String>) {
    left = left + (right ?? "")
}

Then your function becomes:然后你的 function 变成:

func exercise() {
    let alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
   var result = ""
   for _ in 1...6 {
    result += alphabet.randomElement()
   }
   print(result)
}

Yet another way would be to shuffle your source array, fetch the first 6 elements, and then join them back together into a String:另一种方法是打乱您的源数组,获取前 6 个元素,然后将它们重新组合成一个字符串:

func exercise() {
    let alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
    
    let result = alphabet
        .shuffled()[1...6]
        .joined()
    print(result)
}

Give default value to variables by using??通过使用为变量赋予默认值?? operator in case of nil.运算符在 nil 的情况下。 It will change type of variables from String?它会改变String的变量类型吗? to String到字符串

func exercise() {

    let alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

    var char0 = alphabet.randomElement() ?? ""
    var char1 = alphabet.randomElement() ?? ""
    var char2 = alphabet.randomElement() ?? ""
    var char3 = alphabet.randomElement() ?? ""
    var char4 = alphabet.randomElement() ?? ""
    var char5 = alphabet.randomElement() ?? ""

    print(char0 + char1 + char2 + char3 + char4 + char5)
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 二元运算符“+”不能应用于“_”和“String”类型的操作数 - Binary operator '+' cannot be applied to operands of type '_' and 'String' 二元运算符“==”不能应用于“[String]”和“String”类型的操作数 - Binary operator '==' cannot be applied to operands of type '[String]' and 'String 二进制运算符&#39;+&#39;不能应用于&#39;String&#39;和&#39;()-&gt; String&#39;类型的操作数 - Binary operator '+' cannot be applied to operands of type 'String' and '() -> String' 二进制运算符&#39;〜=&#39;不能应用于&#39;String&#39;和&#39;String?&#39;类型的操作数 - Binary operator '~=' cannot be applied to operands of type 'String' and 'String?' 二进制运算符“ +”不能应用于类型为“字符串”和“字符串感叹号”的操作数 - Binary operator '+' cannot be applied to operands of type 'String' and 'String exclamationmark 二进制运算符&#39;==&#39;不能应用于&#39;NSObject&#39;和&#39;String&#39;类型的操作数 - Binary operator '==' cannot be applied to operands of type 'NSObject' and 'String' 二进制运算符-不能应用于字符串类型的操作数! 和诠释 - Binary operator - cannot be applied to operands of type String! and Int 二进制运算符&#39;==&#39;不能应用于&#39;Any?&#39;类型的操作数 和&#39;String&#39;Swift iOS - Binary operator '==' cannot be applied to operands of type 'Any?' and 'String' Swift iOS 二进制运算符&#39;==&#39;不能应用于类型&#39;UIImage?&#39;的操作数 和“字符串”-Swift 4 - Binary operator '==' cannot be applied to operands of type 'UIImage?' and 'String' - Swift 4 Swift-二进制运算符&#39;&gt; =&#39;不能应用于类型为&#39;String&#39;和&#39;Int&#39;的操作数 - Swift - Binary operator '>=' cannot be applied to operands of type 'String' and 'Int'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM