在enum中使用初始化式并赋值给self



my code:

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。

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

谢谢。

你得到这个错误是因为你没有在"default"情况下定义self

要删除错误,定义一个类似的情况(例如。none)并将其放在"default"中。或者你可以创建可失败的初始化器(init?),然后在默认情况下将self定义为nil。

错误是因为您没有在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
        }
    }
}

最新更新