This error message appears when you try to assign a non-literal value to an enum case in Swift. In Swift, enum cases can have associated values, but these values must be literals or derived from other literals.

Here's an example of valid enum cases with associated values:

enum Result {
    case success(message: String)
    case failure(errorCode: Int)
}

In the above example, the associated values for the enum cases ('message' and 'errorCode') are both literals or derived from literals.

However, if you try to assign a non-literal value to an enum case, you will encounter the 'Raw value for enum case must be a literal' error message. For example:

enum Result {
    case success(message: String)
    case failure(errorCode: Int) = getErrorCode() // Error: Raw value for enum case must be a literal
}

func getErrorCode() -> Int {
    return 404
}

In the above example, the 'failure' case is trying to assign the result of the getErrorCode() function as its raw value. Since the function call is not a literal, it results in a compilation error.

To resolve this error, you should either use literal values or derived values from literals for the enum cases with associated values.

Swift Enum Error: Raw Value Must Be a Literal

原文地址: https://www.cveoy.top/t/topic/hf0e 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录