randomElement
is a requirement of the Collection
protocol, as you can see here.
So String
is merely conforming to Collection
by implementing this method, and the documentation comment is just a copy-paste from the original one in Collection
.
If you read the documentation comment in the context of Collection
instead of String
, it makes a lot more sense. It's saying that if self
is also a RandomAccessCollection
, then it's O(1), otherwise it's O(n).
String
does not conform to RandomAccessCollection
, as you can see here, so String.randomElement
is O(n).
EDIT:
To check if something is a RandomAccessCollection
of Character
, you can't do it directly with is
, because RandomAccessCollection
has associated types. One way to do this is to define a function that accepts a constrained type parameter:
let letters = Array("abcdefghijklmnopqrstuvwxyz")
func f<T>(_ x: T) where T : RandomAccessCollection, T.Element == Character {}
f(letters) // if this compiles, then Array<Character> conforms to RandomAccessCollection and Element is Character