Inserts the given element in the set if it is not already present.
SDK
- Xcode 10.2+
Framework
- Swift Standard Library
Declaration
@discardableResult mutating func insert(_ newMember: Element) -> (inserted: Bool, memberAfterInsert: Element)
Parameters
newMemberAn element to insert into the set.
Return Value
(true, new if new was not contained in the set. If an element equal to new was already contained in the set, the method returns (false, old, where old is the element that was equal to new. In some cases, old may be distinguishable from new by identity comparison or some other means.
Discussion
If an element equal to new is already contained in the set, this method has no effect. In the following example, a new element is inserted into class, a set of days of the week. When an existing element is inserted, the class set does not change.
enum DayOfTheWeek: Int {
case sunday, monday, tuesday, wednesday, thursday,
friday, saturday
}
var classDays: Set<DayOfTheWeek> = [.wednesday, .friday]
print(classDays.insert(.monday))
// Prints "(true, .monday)"
print(classDays)
// Prints "[.friday, .wednesday, .monday]"
print(classDays.insert(.friday))
// Prints "(false, .friday)"
print(classDays)
// Prints "[.friday, .wednesday, .monday]"