首页 > 解决方案 > Swift 编译器错误:无法将类型“()”的值转换为指定类型“字符串”

问题描述

我正在使用 Swift Playgrounds 并在Intro to Swift的第 9 课中学习参数的第 9 课中学习参数。

func sing(verb: String, noun: String) {
    print("\(verb), \(verb), \(verb) your \(noun)")
}

let line = sing(verb: "Row", noun: "Boat")

最后一行给了我这个警告:

常量 'line' 推断为具有类型 '()',这可能是出乎意料的。

当我将常量明确定义为字符串时——<code>let line: String = sing(verb: "Row", noun: "Boat")——我得到以下错误:

错误:无法将类型“()”的值转换为指定类型“字符串”

我不知道该怎么做才能解决这个问题。

旁注:如果您对如何使函数读起来更像句子有任何建议,我将不胜感激!

标签: swiftswift-playground

解决方案


您的函数sing()没有返回String对象。

因此,您不能使用variable = void function()它,因为它不是有效的赋值操作。

您可以将String返回类型指定为sing(),并返回您在函数中打印的字符串。这将解决你的问题。

func sing(verb: String, noun: String) -> String {   
  return "\(verb), \(verb), \(verb) your \(noun)"     
}

let line = sing(verb: "Row", noun: "Boat")

推荐阅读