0%

Custom expression pattern

// 自定义表达式模式
struct Student {
    var score = 0, name = ""
    
    /// pattern: case 后面内容
    /// value: switch 后面内容
    static func ~=(pattern: Int, value: Student) -> Bool {
        return value.score >= pattern
    }
    
    static func ~=(pattern: Range<Int>, value: Student) -> Bool {
        return pattern.contains(value.score)
    }
    
    static func ~=(pattern: ClosedRange<Int>, value: Student) -> Bool {
        return pattern.contains(value.score)
    }
}

var stu = Student(score: 75, name: "Tom")
switch stu {
case 100:
    print(">=100")
case 90:
    print(">=90")
case 80..<90:
    print("[80, 90]")
case 60...79:
    print("[60, 79]")
case 0:
    print(">=0")
default:
    break
}

extension String {
    static func ~=(pattern: (String) -> String, value: String) -> Bool {
        return pattern(value)
    }
}

func hasPrefix(_ prefix: String) -> ((String) -> Bool) {
    return { $0.hasPrefix(prefix) }
}
func hasSuffix(_ suffix: String) -> ((String) -> Bool) {
    return { $0.hasSuffix(suffix) }
}

var fn = hasPrefix("123")
print(fn("123456"))

var str = "123456"
switch str {
case hasPrefix("123"), hasSuffix("456"):
    print("123开头")
    print("456结尾")
default:
    break
}

func isEven(_ i: Int) -> Bool {
    return i % 2 == 0
}

func isOdd(_ i: Int) -> Bool {
    return i % 2 != 0
}

extension Int {
    static func ~=(pattern: (Int) -> Bool, value: Int) -> Bool {
        return pattern(value)
    }
}

var age = 9
switch age {
case isEven: //函数匹配,函数类型
    print(age,"是个偶数")
case isOdd:
    print(age,"是个奇数")
default:
    break
}

–EOF–