如何返回数组?

时间:2019-06-20 15:32:10

标签: arrays swift

我需要编写一个应用程序,该应用程序使用输入到文本字段中的字符串并使用它来调用同义词库功能。该函数必须返回一个包含该字符串同义词的数组,但是我似乎遇到了一些语法问题。有人可以借一双眼睛吗?

我已经检查了变量的语法和范围,但是我似乎不明白我在哪里弄错了。

var synonymsDictionary = ["swift" : ["abrupt", "expeditious", "hasty", "nimble", "quick", "rapid", "speedy", "sudden", "unexpected"],
                          "objective" : ["detached", "disinterested", "dispassionate", "equitable", "evenhanded", "nonpartisan", "open-minded", "unbiased"],
                          "calculate" : ["adjust", "appraise", "consider", "count", "determine", "forecast", "gauge", "guess", "measure", "multiply", "reckon", "subtract", "tally", "weigh", "work out"],
                          "create" : ["build", "conceive", "constitute", "construct", "design", "devise", "discover", "establish", "forge", "form"]]

func synonyms(for term: String) -> String {

    if let sameWords = synonymsDictionary[term] {
        print("These are the synonyms for \(term): \(sameWords)")
    } else {
        print("This word doesn't have any synonyms.")
    }
    let result = synonymsDictionary[term]
    return result
}
synonyms(for: "objective")

我应该得到一个数组,其中包含我输入的术语(string)的同义词。错误

  

无法转换'[String]类型的返回表达式?”返回类型“ String”

1 个答案:

答案 0 :(得分:1)

当前,您返回String,但它应该是数组[String],请尝试

func synonyms(for term: String) -> [String] {
   return synonymsDictionary[term] ?? []
}

还保留对返回值的引用

let res = synonyms(for: "objective")
print(res)

由于synonymsDictionary是字典[String:[String]],因此每个值都是[String]类型,在返回值String类型的函数中不能返回