Skip to content

Commit 063d926

Browse files
committed
[stdlib] Dictionary: Add implementation for first
This is primarily for documentation purposes, although the default implementation (based on an iterator) may not return the correct value for bridged dictionaries with exotic implementations.
1 parent 6ee9fce commit 063d926

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

stdlib/public/core/Dictionary.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -707,6 +707,21 @@ extension Dictionary: Collection {
707707
public var isEmpty: Bool {
708708
return count == 0
709709
}
710+
711+
/// The first element of the dictionary.
712+
///
713+
/// The first element of the dictionary is not necessarily the first element
714+
/// added to the dictionary. Don't expect any particular ordering of
715+
/// dictionary elements.
716+
///
717+
/// If the dictionary is empty, the value of this property is `nil`.
718+
@inlinable
719+
public var first: Element? {
720+
// FIXME: It'd better to use an iterator than to subscript with startIndex,
721+
// because startIndex is currently O(n) in bridged dictionaries. However,
722+
// enumerators aren't guaranteed to have the same element order as allKeys.
723+
return count > 0 ? self[startIndex] : nil
724+
}
710725
}
711726

712727
extension Dictionary {

stdlib/public/core/Set.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,9 @@ extension Set: Collection {
384384
/// If the set is empty, the value of this property is `nil`.
385385
@inlinable
386386
public var first: Element? {
387+
// FIXME: It'd better to use an iterator than to subscript with startIndex,
388+
// because startIndex is currently O(n) in bridged sets. However,
389+
// enumerators aren't guaranteed to have the same element order as allKeys.
387390
return count > 0 ? self[startIndex] : nil
388391
}
389392
}

0 commit comments

Comments
 (0)