swift - Enum parameter for function
问题描述
enum FooEnum: Int {
case fooEnumCase = 13512
case fooEnumCase2 = 425156
}
class FooClass {
public func myFunction(chosenEnumCase: fooEnum) -> String {
/* Logic */
}
}
fooClass.myFunction(fooEnum.fooEnumCase)
I am getting the error:
FooEnum
is not convertible toFooClass
What is wrong with this code?
解决方案
To explain the error message let's consider fooClass.myFunction
:
let f: (fooClass) -> ((fooEnum) -> String) = fooClass.myFunction
It's a function that expects an instance of fooClass
, and returns another function ((fooEnum) -> String)
. Whereas in your code it is fed an instance of type fooEnum
.
Call that function on a instance:
let myInstance = fooClass()
myInstance.myFunction(chosenEnumCase: fooEnum.fooEnumCase)
Or make myFunction
a class function:
public class func myFunction(chosenEnumCase: fooEnum) -> String
PS: To conform to the Swift naming conventions use FooEnum
and FooClass
.
推荐阅读
- node.js - Webpack handlebars-loader 模板文件在 mocha 单元测试中无法解析
- angular - 是否可以覆盖@Component.providers 中的默认对话框选项?
- javascript - 经过文件值到个人
- javascript - 如何在两个不总是矩形的元素之间画一条线(路径,svg)
- php - jQuery Ajax 调用在服务器上出现内部服务器错误,但在 Localhost 上有效
- java - Hibernate 一对多关系
- java - 比较 Jsch Java 中上传和下载的文件
- php - 在 PHP 类路由器中添加 404 规则
- python - 保留满足条件的行和相邻行
- javascript - 如何在 JavaScript 中获取最近的 span 元素