首页 > 解决方案 > 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 to FooClass

What is wrong with this code?

标签: swift

解决方案


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.


推荐阅读