Skip to content

Commit 2b95449

Browse files
Switch .first to use an index not an iterator (#18075)
1 parent b63ac32 commit 2b95449

File tree

1 file changed

+3
-17
lines changed

1 file changed

+3
-17
lines changed

stdlib/public/core/Collection.swift

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1210,24 +1210,10 @@ extension Collection {
12101210
/// // Prints "10"
12111211
@inlinable
12121212
public var first: Element? {
1213-
@inline(__always)
1214-
get {
1215-
// NB: Accessing `startIndex` may not be O(1) for some lazy collections,
1216-
// so instead of testing `isEmpty` and then returning the first element,
1217-
// we'll just rely on the fact that the iterator always yields the
1218-
// first element first.
1219-
var i = makeIterator()
1220-
return i.next()
1221-
}
1213+
let start = startIndex
1214+
if start != endIndex { return self[start] }
1215+
else { return nil }
12221216
}
1223-
1224-
// TODO: swift-3-indexing-model - uncomment and replace above ready (or should we still use the iterator one?)
1225-
/// Returns the first element of `self`, or `nil` if `self` is empty.
1226-
///
1227-
/// - Complexity: O(1)
1228-
// public var first: Element? {
1229-
// return isEmpty ? nil : self[startIndex]
1230-
// }
12311217

12321218
/// A value less than or equal to the number of elements in the collection.
12331219
///

0 commit comments

Comments
 (0)