如何从Swift集合中获取多个随机元素?

发布于 2025-02-04 20:21:29 字数 185 浏览 3 评论 0原文

我有一个set,其中包含多个elements。我的目标是从中获得10个随机元素

我如何以最简单的方式(希望是一行)实现此目标,而无需修改set set本身或创建新的参考set

I have a Set which contains multiple Elements. My goal is to get 10 random Elements out of it.

How can I achieve this goal in the simplest way (hopefully one line) without having to modify the Set itself or create a new reference Set?

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

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

发布评论

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

评论(1

风追烟花雨 2025-02-11 20:21:29

这是我想到的最短的单线:

let randomTenElements = mySet.lazy.shuffled().prefix(10)

它返回arrayslice,因此,如果您需要结果作为数组或另一组,则必须将其显式地施放为所需的类型。

Here's the shortest one-liner I came up with:

let randomTenElements = mySet.lazy.shuffled().prefix(10)

It returns an ArraySlice though so if you need the result as an array or another set you'll have to explicitly cast it to your desired type.

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