在枚举中使用初始化程序并分配给self

时间:2016-08-25 12:31:36

标签: swift

我的代码:

enum Grade: String{
    case A, B, C, D, E, F, U, S
    init!(_ result: Int){
        if result > 100 {
            return nil
        }
        switch result {
        case 0:
            self = .U
        case 1...49:
            self = .F
        case 0:
            self = .U
        case 50...59:
            self = .E
        case 60...69:
            self = .D
        case 70...79:
            self = .C
        case 80...89:
            self = .B
        case 90...99:
            self = .A
        case 100:
            self = .S
        default:
            break
        }
    }
}

看起来不错,但我收到了错误。

错误:在初始化所有存储属性之前使用'self'。

我修复它的方法是在初始化程序中为self指定一些东西,然后使用switch。

我想知道是否有更好的解决方案?

感谢。

2 个答案:

答案 0 :(得分:2)

你得到了这个错误,因为你没有在"默认"中定义自己。情况下

要删除错误,请再定义一个案例(例如.None)并将其放入"默认"。或者您可以创建可用的初始化程序(init?),然后在默认情况下将self定义为nil。

答案 1 :(得分:0)

错误是因为您没有在default语句中指定返回值。你的也是init!对我来说毫无意义。

试试这个:

enum Grade: String {
    case A, B, C, D, E, F, U, S

    init?(_ result: Int){
        guard 0...100 ~= result else {
            return nil
        }

        switch result {
        case 0:
            self = .U
        case 1...49:
            self = .F
        case 50...59:
            self = .E
        case 60...69:
            self = .D
        case 70...79:
            self = .C
        case 80...89:
            self = .B
        case 90...99:
            self = .A
        case 100:
            self = .S
        default:
            return nil
        }
    }
}

您可以将低于0的分数视为0,将100以上的分数视为100:

,使其不可为空
enum Grade: String {
    case A, B, C, D, E, F, U, S

    init (_ result: Int) {
        switch result {
        case Int.min...0:
            self = .U
        case 1...49:
            self = .F
        case 50...59:
            self = .E
        case 60...69:
            self = .D
        case 70...79:
            self = .C
        case 80...89:
            self = .B
        case 90...99:
            self = .A
        case 100..<Int.max: // 100...Int.max is a bug in Swift 2, fixed in Swift 3
            self = .S
        default:
            self = .U // Even though all the cases above are exhaustive, the compiler
                      // does not know that. Hence, we still need a default, but it
                      // will never be reached
        }
    }
}
相关问题