AttributedString literal?

"nam" + "e\u{0301}"

This is supposed to be equivalent to a single-piece string literal. But my code:

let decomposedLiteral: NameToken = "nam" + "e\u{0301}"

Had an error of “Cannot convert value of type 'AttributedString' to specified type 'NameToken'“. Using an actual one-piece literal:

let decomposedLiteral: NameToken = "name\u{0301}"

worked. Why was that literal expression considered an AttributedString? The code was part of a test for NameToken'sExpressibleByStringLiteraluse.

AFAIK you can't build a string literal like that. String literals need to be known at compile time, so Swift would need to know the result of "nam" + "e\u{0301}" at compile time.

In order to do that, it'd need to apply the +(_:,_:) operator (which is just a "regular" Swift function) to the two "nam" and "e\u{0301}" arguments. And Swift can't do that kind of compile-time execution yet.

(Actually, the type checker would need to be able to execute at compile time any other +(_:,_;) operator that can be applied on String/StringLiteral arguments!).


As to why the result of "nam" + "e\u{0301}" is inferred to be AttributedString instead of String in your code: it must be because of something else in the surrounding code. A minimal example isn't inferred to be AttributedString:

struct Foo: ExpressibleByStringLiteral {
    init(stringLiteral value: StringLiteralType) {}
}

let foo: Foo = "nam" + "e\u{0301}" // ❌ Cannot convert value of type 'String' to specified type 'Foo'
3 Likes

By definition, an expression is not a literal.

1 Like