Skip to content

Commit aaaea05

Browse files
authored
Merge pull request #9169 from moiseev/joined-4
2 parents cfd2d2c + 5c263b7 commit aaaea05

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

stdlib/public/core/String.swift

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -566,6 +566,11 @@ extension Sequence where Iterator.Element == String {
566566
/// in this sequence. The default separator is an empty string.
567567
/// - Returns: A single, concatenated string.
568568
public func joined(separator: String = "") -> String {
569+
return _joined(separator: separator)
570+
}
571+
572+
@inline(__always)
573+
internal func _joined(separator: String = "") -> String {
569574
var result = ""
570575

571576
// FIXME(performance): this code assumes UTF-16 in-memory representation.
@@ -607,6 +612,30 @@ extension Sequence where Iterator.Element == String {
607612
}
608613
}
609614

615+
616+
// This overload is necessary because String now conforms to
617+
// BidirectionalCollection, and there are other `joined` overloads that are
618+
// considered more specific. See Flatten.swift.gyb.
619+
extension BidirectionalCollection where Iterator.Element == String {
620+
/// Returns a new string by concatenating the elements of the sequence,
621+
/// adding the given separator between each element.
622+
///
623+
/// The following example shows how an array of strings can be joined to a
624+
/// single, comma-separated string:
625+
///
626+
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
627+
/// let list = cast.joined(separator: ", ")
628+
/// print(list)
629+
/// // Prints "Vivien, Marlon, Kim, Karl"
630+
///
631+
/// - Parameter separator: A string to insert between each of the elements
632+
/// in this sequence. The default separator is an empty string.
633+
/// - Returns: A single, concatenated string.
634+
public func joined(separator: String = "") -> String {
635+
return _joined(separator: separator)
636+
}
637+
}
638+
610639
#if _runtime(_ObjC)
611640
@_silgen_name("swift_stdlib_NSStringLowercaseString")
612641
func _stdlib_NSStringLowercaseString(_ str: AnyObject) -> _CocoaString

test/stdlib/StringAPI.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,11 @@ StringTests.test("String.init(_:String)") {
365365
let _: String = String("" as String) // should compile without ambiguities
366366
}
367367

368+
StringTests.test("[String].joined() -> String") {
369+
let s = ["hello", "world"].joined()
370+
_ = s == "" // should compile without error
371+
}
372+
368373
var CStringTests = TestSuite("CStringTests")
369374

370375
func getNullUTF8() -> UnsafeMutablePointer<UInt8>? {

0 commit comments

Comments
 (0)