有没有一种方法可以使用' is'用随机计算键入操作员?

发布于 2025-01-20 15:48:18 字数 324 浏览 1 评论 0原文

我在“if”条件下收到以下错误:

“协议“RandomAccessCollection”只能用作通用约束,因为它具有 Self 或关联的类型要求”

let str = "mystring"

let v = str.utf8

if v is RandomAccessCollection {
    print("YES")
} else {
    print("NO")
}

出于好奇,有没有办法使用“is”类型检查运算符来检查对象/实例是否符合 RandomAccessCollection?

I'm getting the following error on the 'if' condition:

"Protocol 'RandomAccessCollection' can only be used as a generic constraint because it has Self or associated type requirements"

let str = "mystring"

let v = str.utf8

if v is RandomAccessCollection {
    print("YES")
} else {
    print("NO")
}

Out of curiosity, is there a way to use the "is" type check operator to check if an object/instance conforms to RandomAccessCollection?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

成熟稳重的好男人 2025-01-27 15:48:18

这些类型的检查在运行时 unswifty 。不要那样做。

一种可能的方法是方法过载,检查以编译时间进行进行检查,例如,

func checkType<T>(obj: T) {
    print("NO")
}

func checkType<T:RandomAccessCollection>(obj: T) {
    print("YES")
}

let str = "mystring"
let v = str.utf8
checkType(obj: v) // prints NO

let x = Data(v)
checkType(obj: x)  // prints YES

如果对象符合协议,则将第二种方法称为第一个方法。

These type checks at runtime are unswifty. Don't do that.

A possible way is method overloading, the check is performed at compile time for example

func checkType<T>(obj: T) {
    print("NO")
}

func checkType<T:RandomAccessCollection>(obj: T) {
    print("YES")
}

let str = "mystring"
let v = str.utf8
checkType(obj: v) // prints NO

let x = Data(v)
checkType(obj: x)  // prints YES

If the object conforms to the protocol the second method is called otherwise the first.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文