本文介绍了检查一个范围是否在另一个范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
let smallRange = 1..<2
let largeRange = 0..<10
largeRange ~= smallRange // False
为什么要先编译这个!?但如果它编译,答案应该是 True
Why does this compile at the first place!? But if it compiles the answer should be True
下一个代码有效:
smallRange.clamped(to: largeRange) == smallRange // True有没有更简单的检查方法?
Is there any simpler way to check?
推荐答案我不认为你会找到一个更简单"的或更短"写这个的方式,但你可以定义你自己的模式匹配运算符来缩短你的代码:
I don't think you will find a "simpler" or "shorter" way of writing this but you can define your own pattern matching operator to shorten your code:
extension Range { static func ~=(lhs: Self, rhs: Self) -> Bool { rhs.clamped(to: lhs) == rhs } } extension ClosedRange { static func ~=(lhs: Self, rhs: Self) -> Bool { rhs.clamped(to: lhs) == rhs } } let smallRange = 1..<2 let largeRange = 0..<10 smallRange ~= largeRange // false largeRange ~= smallRange // true注意:它编译是因为有一个通用实现用于检查相等性,例如切换字符串,因此只有在两个范围相同时它才会返回 true.
Note: It compiles because there is a generic implementation used to check for equality like switching a string therefore it would only return true if both ranges were the same.
func ~= <T>(a: T, b: T) -> Bool where T : Equatable更多推荐
检查一个范围是否在另一个范围内
发布评论