當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Swift Set union(_:)用法及代碼示例

實例方法

union(_:)

返回包含此集合和給定序列的元素的新集合。

聲明

func union<S>(_ other: S) -> Set<Element> where Element == S.Element, S : Sequence
Element 符合 Hashable 時可用。

返回值

具有此集合的獨特元素和 other 的新集合。

參數

other

一係列元素。 other 必須是有限的。

詳述

在以下示例中,attendeesAndVisitors 集由 attendees 集和 visitors 數組的元素組成:


let attendees: Set = ["Alicia", "Bethany", "Diana"]
let visitors = ["Marcia", "Nathaniel"]
let attendeesAndVisitors = attendees.union(visitors)
print(attendeesAndVisitors)
// Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"

如果該集合已包含一個或多個也在 other 中的元素,則保留現有成員。如果other 包含等效元素的多個實例,則僅保留第一個實例。


let initialIndices = Set(0..<5)
let expandedIndices = initialIndices.union([2, 3, 6, 6, 7, 7])
print(expandedIndices)
// Prints "[2, 4, 6, 7, 0, 1, 3]"

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相關用法


注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Set union(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。