〜= Swift中的运算符 [英] ~= operator in Swift
本文介绍了〜= Swift中的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我最近从Apple下载了高级NSOperations 示例应用,发现此代码...
I recently downloaded the Advanced NSOperations sample app from Apple and found this code...
// Operators to use in the switch statement.
private func ~=(lhs: (String, Int, String?), rhs: (String, Int, String?)) -> Bool {
return lhs.0 ~= rhs.0 && lhs.1 ~= rhs.1 && lhs.2 == rhs.2
}
private func ~=(lhs: (String, OperationErrorCode, String), rhs: (String, Int, String?)) -> Bool {
return lhs.0 ~= rhs.0 && lhs.1.rawValue ~= rhs.1 && lhs.2 == rhs.2
}
似乎使用〜=
运算符字符串
和 Ints
但我从未见过它之前。
It seems to use the ~=
operator against Strings
and Ints
but I've never seen it before.
这是什么?
推荐答案
这是一个运算符用于 case
语句中的模式匹配。
It is an operator used for pattern matching in a case
statement.
您可以在这里了解如何使用和利用它来提供您自己的实现:
You can take a look here to know how you can use and leverage it providing your own implementation:
- http://oleb.net/blog/2015 / 09 / swift-pattern-matching /
- http://austinzheng.com/2014/12/17/custom-pattern-matching/
- http://oleb.net/blog/2015/09/swift-pattern-matching/
- http://austinzheng.com/2014/12/17/custom-pattern-matching/
这是一个定义自定义并使用它的简单示例:
Here is a simple example of defining a custom one and using it:
struct Person {
let name : String
}
// Function that should return true if value matches against pattern
func ~=(pattern: String, value: Person) -> Bool {
return value.name == pattern
}
let p = Person(name: "Alessandro")
switch p {
// This will call our custom ~= implementation, all done through type inference
case "Alessandro":
print("Hey it's me!")
default:
print("Not me")
}
// Output: "Hey it's me!"
if case "Alessandro" = p {
print("It's still me!")
}
// Output: "It's still me!"
这篇关于〜= Swift中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文