检查一个范围是否在另一个范围内

编程入门 行业动态 更新时间:2024-10-11 01:10:24
本文介绍了检查一个范围是否在另一个范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 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

更多推荐

检查一个范围是否在另一个范围内

本文发布于:2023-11-07 19:21:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567202.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:范围内

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!