在 Swift 中创建绑定到特定范围的类型 [英] Creating a type bound to a certain range in Swift

查看:28
本文介绍了在 Swift 中创建绑定到特定范围的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个接受 Int 的函数,但不只是任何 Int.可能是:

Say I have a function that takes an Int, but not just any Int. It could be:

  • 只有自然数
  • Ints 从 2 到 200

假设有效值的数量太大,无法使用 Enum 明确声明所有这些都是可行的方法.

Assume that the number of valid values is too big to make the use of an Enum that explicitly declares all of them a feasible approach.

有没有办法在 Swift 中声明一个指定封闭范围的类型?

Is there a way to declare a type that specifies a closed range in Swift?

我尝试使用 Range,但它没有按预期工作.

I tried playing around with Range, but it doesn't work as expected.

推荐答案

我能想到的最好的方法是将 Int 包装在一个结构中,并带有一个强制执行您的条件的初始化程序:

The best I can think of is to wrap an Int in a struct with an initializer that enforces your condition:

struct NameMe {
    let value: Int

    init?(_ value: Int) {
        guard 2...200 ~= value else { return nil }
        self.value = value
    }
}

虽然单独使用 Int 需要在每个需要这种类型的值的地方进行运行时条件检查,但这种技术仅限于在第一个创建此类值的地方地方.创建后,您可以传递 NameMe 实例,知道它们的值满足先决条件.

Whereas using Int alone would require a run-time condition check at every place a value of such a kind was needed, this technique limits this to only the places where such values are created in the first place. Once created, you can pass around NameMe instances around, knowing that their value meets the preconditions.

这篇关于在 Swift 中创建绑定到特定范围的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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