Skip to content

Commit 109c213

Browse files
Max Moiseevmoiseev
authored andcommitted
[stdlib] Prioritizing non-failing String.init_:String)
1 parent cce957b commit 109c213

File tree

3 files changed

+12
-9
lines changed

3 files changed

+12
-9
lines changed

stdlib/public/core/String.swift

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,12 @@ public protocol StringProtocol
7878
) rethrows -> Result
7979
}
8080

81+
extension StringProtocol /* : LosslessStringConvertible */ {
82+
public init?(_ description: String) {
83+
self.init(description.characters)
84+
}
85+
}
86+
8187
/// Call body with a pointer to zero-terminated sequence of
8288
/// `TargetEncoding.CodeUnit` representing the same string as `source`, when
8389
/// `source` is interpreted as being encoded with `SourceEncoding`.
@@ -1023,12 +1029,6 @@ extension String : CustomStringConvertible {
10231029
}
10241030
}
10251031

1026-
extension String : LosslessStringConvertible {
1027-
public init?(_ description: String) {
1028-
self = description
1029-
}
1030-
}
1031-
10321032
extension String {
10331033
@available(*, unavailable, renamed: "append(_:)")
10341034
public mutating func appendContentsOf(_ other: String) {

stdlib/public/core/StringRangeReplaceableCollection.swift.gyb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,8 @@ extension String : StringProtocol {
4141
// - init<S>(_ characters: S) where S : Sequence, S.Iterator.Element == Character
4242
// Cannot simply do init(_: String) as that would itself be ambiguous with
4343
// init?(_ description: String)
44-
public init<T : StringProtocol>(_ other: T) {
45-
self.init(other.characters)
44+
public init(_ other: String) {
45+
self.init(other._core)
4646
}
4747

4848
/// The position of the first character in a nonempty string.

test/stdlib/StringAPI.swift

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -362,9 +362,12 @@ StringTests.test("CompareStringsWithUnpairedSurrogates")
362362
}
363363

364364
StringTests.test("String.init(_:String)") {
365-
let _: String = String("" as String) // should compile without ambiguities
365+
var s = String("")
366+
expectType(String.self, &s)
367+
var _ = String("") as String? // should also compile, but not be the default
366368
}
367369

370+
368371
StringTests.test("[String].joined() -> String") {
369372
let s = ["hello", "world"].joined()
370373
_ = s == "" // should compile without error

0 commit comments

Comments
 (0)