Why String `dropLast(_ k: Int) [Character]` is shown in auto complete list? Doesn't seem to exist according to the doc

I'm seeing this extra dropLast(_ k: Int) [Character] method:

Don't see such method in String doc

Sequence.dropLast(_:)

So which one is it calling? Is it inferring the type from the call site to decide?

I do this:

String(text.dropLast(selectionEndOffset - selectionStartOffset))

since there is no String.init() that takes [Character], so it's calling the Substring one?

That I don't exactly know. It could be either a substring pair (String.init, String.dropLast) or an array pair (String.init, Sequence.dropLast) as Array is a Sequence too. Since they have different numbers of generics/protocol requirements, it is probably unambiguous to the compiler (and it'd complain otherwise).

Usually, it doesn't matter, but if you're concerned about the overload used, you can also guide the type checker:

String(a.dropLast(2) as Substring)
String(a.dropLast(2) as Array)

:pleading_face: So I was wrong: there are two String.init's this can resolved to. Maybe one is marked with @_disfavored_overload?

The more constrained one is called, unless you (or the call site) explicitly specify.

"foo".dropLast(1) // Substring
"foo".dropLast(1) as [Character] // [Character]

// Either Substring or [Character] is acceptable so Substring is preferred.
String("foo".dropLast(1)) // Substring

func f<T>(x: [T]) {}

// can only be [Character]
f(x: "foo".dropLast(1)) // [Character]

Yea, you don't need the thing for every human-level ambiguity. It can easily subvert user's expectations and tend to be used sparingly. In fact, it'd actually be weird if they tailored these overloads around these interactions.

Terms of Service

Privacy Policy

Cookie Policy