检查一个范围是否在另一个范围内 [英] Check if one Range is within another

查看:58
本文介绍了检查一个范围是否在另一个范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于检查一个范围是否在另一个范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆