swift - 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")——我得到以下错误:
错误:无法将类型“()”的值转换为指定类型“字符串”
我不知道该怎么做才能解决这个问题。
旁注:如果您对如何使函数读起来更像句子有任何建议,我将不胜感激!
解决方案
您的函数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")
推荐阅读
- javascript - 在可观察数组中的项目发生更改后,Mobx 不会重新渲染
- android - Android Room Database:如何按名称按字母顺序查询?
- sql - postgres:函数年龄的索引:错误:索引表达式中的函数必须标记为 IMMUTABLE
- java - 如何在 itext 连字符自动西里尔文中使用它
- javascript - 在清除的字符串中异步连接单击的数字
- javascript - HTML 函数编辑
- ios - 来自此 ios 客户端应用程序的请求
被封锁 - java - 在 Nox(Android 模拟器)中运行 java .class/.jar 文件
- react-native - 组件不会被包裹在边界内(React Native)
- c++ - PostgreSQL C 扩展函数返回成对向量或文本数组