Swift [String]不能转换为'String'

时间:2014-12-18 19:56:57

标签: arrays string swift

尝试让它工作但我收到错误

“[String]不能转换为'String'”

 var city = "Atlanta"
 var issueLocation = ["Atlanta","Montreal","Toronto","XXIIVV"]
 let locationRand = Int(arc4random() % 3)
 var passportIdent = "Issue Location: \(issueLocation[locationRand])"
 if (issueLocation == city){
  }

3 个答案:

答案 0 :(得分:3)

您正在将字符串数组与单个字符串进行比较。这没有意义,因此swift编译器正在抱怨。

issueLocation是字符串的数组,swift表示为[String]
另一方面,city是一个String。请注意缺少的方括号。

将字符串数组与单个字符串进行比较是没有意义的。一件事怎么能等于很多东西?

那是错误。目前还不清楚你要完成什么(你应该告诉我们),所以我无法帮助你。

答案 1 :(得分:1)

看看你的if语句:

if (issueLocation == city){
}

“city”是一个字符串,而“issueLocation”是一个字符串数组。您正在尝试将字符串与数组进行比较,这将无法正常工作。

答案 2 :(得分:1)

var city = "Atlanta"
var issueLocation = ["Atlanta","Montreal","Toronto","XXIIVV"]
let locationRand = Int(arc4random() % 3)
var passportIdent = "Issue Location: \(issueLocation[locationRand])"
if (issueLocation == city){
}

应该是

var city = "Atlanta"
var issueLocation = ["Atlanta","Montreal","Toronto","XXIIVV"]
let locationRand = Int(arc4random() % 3)
var passportIdent = "Issue Location: \(issueLocation[locationRand])"
var randCity = issueLocation[locationRand]
if (randCity== city){
}

注意该行

var randCity = issueLocation[locationRand]

实际上在您的issueLocation数组中获取随机元素。然后,您可以使用该值与city变量进行比较。