【问题标题】:swift binary operator cannot be applied to operands快速二元运算符不能应用于操作数
【发布时间】:2016-08-17 08:25:26
【问题描述】:

我请求快速学习 swift,我在 appStore 上以 5 美元的价格购买了一款名为 CODESWIFT 的应用。我认为这是从语言开始,熟悉命名事物的新方法等等的一种很好的简单方法......在其中一个练习中,应用程序让您创建这几个变量并将它们组合起来打印到控制台:

var company = "Apple"

let yearFounded = 1976

var str = "was founded in "

print(company + str + yearFounded)

当我在应用程序上执行此操作时,它可以工作(应用程序没有明显编译,但它会检查您的代码),但我决定在 Xcode 上运行相同的练习,但它返回错误:

"binary operator '+' cannot be applied to operands of type 'String' and 'Int' 

这似乎是完全合乎逻辑的,但我想我没想到该应用程序会成为骗子。我被抢了 5 美元吗??

【问题讨论】:

标签: swift operand binary-operators


【解决方案1】:

这绝对不是怎么做的。这些都有效:

var company = "Apple"
let yearFounded = 1976
var str = "was founded in"

print("\(company) \(str) \(yearFounded)")
print(company + " " + str + " " + String(yearFounded))
print(company, str, yearFounded)

// three times "Apple was founded in 1976"

【讨论】:

    【解决方案2】:

    您需要将Int 值转换为String 试试这个:

    print(company + str + "\(yearFounded)")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-10
      • 2015-09-01
      • 2018-01-18
      • 2017-11-22
      • 2018-06-23
      • 2023-03-10
      • 2016-03-11
      相关资源
      最近更新 更多