swift-模式匹配 && override ~= operator

Swift的switch使用 ~= 操作符进行模式匹配,case A, A是~=操作符的左参数,switch B, B是~=操作符的右参数。swift隐式调用 ~=操作符。

所以自定义模式匹配的方法如下:

e.g.1

enum Day: Int {
    case Monday, TuesDay, Wednesday, Thursday, Friday, Saturday, Sunday
}
func ~= (lhs:Int, rhs:Day) ->Bool {
    return lhs == rhs.rawValue + 1
}

class Tutorial {
    let day:Day?
    ...
}

extension Tutorial {
    var order: String {
        guard let day = day else {
            return "not scheduled"
        }
        
        switch day {
        case 1:
            return "first"
        case 2:
            return "second"
        case 3:
            return "third"
        case 4:
            return "fourth"
        case 5:
            return "fifth"
        case 6:
            return "sixth"
        case 7:
            return "seventh"
        default:
            fatalError("invalid")
        }
        
    }
} 

 

e.g.2

http://swifter.tips/pattern-match/

posted @ 2018-03-05 16:24  ShellHan  阅读(475)  评论(0编辑  收藏  举报