[stdlib] Allow a default for optional interpolations (#80547)

This adds an `appendInterpolation` overload to
`DefaultStringInterpolation` that includes a parameter for providing a
default string when the value to interpolate is `nil`. This allows this
kind of usage:

```swift
let age: Int? = nil
print("Your age is \(age, default: "timeless")")
// Prints "Your age is timeless"
```

The change includes an additional fixit when optional values are
interpolated, with a suggestion to use this `default:` parameter.
This commit is contained in:
Nate Cook
2025-05-07 12:47:02 -05:00
committed by GitHub
parent 62b7a6f380
commit e68069f891
10 changed files with 248 additions and 58 deletions

View File

@@ -92,6 +92,11 @@ PrintTests.test("StringInterpolation") {
let s2 = "aaa\(1)bbb\(2 as Any)"
expectEqual("aaa1bbb2", s2)
let x: Int? = 1
let y: Int? = nil
let s3 = "aaa\(x, default: "NONE")bbb\(y, default: "NONE")"
expectEqual("aaa1bbbNONE", s3)
}
PrintTests.test("SubstringInterpolation") {
@@ -100,6 +105,11 @@ PrintTests.test("SubstringInterpolation") {
let s2 = "aaa\(1)bbb\(2 as Any)" as Substring
expectEqual("aaa1bbb2", s2)
let x: Int? = 1
let y: Int? = nil
let s3 = "aaa\(x, default: "NONE")bbb\(y, default: "NONE")" as Substring
expectEqual("aaa1bbbNONE", s3)
}
PrintTests.test("CustomStringInterpolation") {
@@ -116,6 +126,11 @@ PrintTests.test("AutoCustomStringInterpolation") {
let s2 = ("aaa\(1)bbb\(2 as Any)" as MySimpleString).value
expectEqual("aaa1bbb2", s2)
let x: Int? = 1
let y: Int? = nil
let s3 = ("aaa\(x, default: "NONE")bbb\(y, default: "NONE")" as MySimpleString).value
expectEqual("aaa1bbbNONE", s3)
}
PrintTests.test("CustomStringInterpolationExtra") {