Skip to content

Invalid lifetime when using UTF8Span from a temporary String value #82022

Closed
@glessard

Description

@glessard

Description

For some reason, UTF8Span.span behaves quite differently from using UTF8View.span where temporary values are concerned.

Reproduction

func intUTF8SpanCount1(_ i: Int) -> Int {
    let span = String(i).utf8Span
    return span.count
}

func intUTF8SpanCount2(_ i: Int) -> Int {
    let span = String(i).utf8Span.span
    return span.count
}

#if false
func intUTF8SpanCount3(_ i: Int) -> Int {
    let span = String(i).utf8.span
    return span.count
}
#endif

(also here: https://swift.godbolt.org/z/zxo6b358f)

After switching the #if clause to true, the third case will fail to compile with a correct escape diagnostic:

<source>:13:9: error: lifetime-dependent variable 'span' escapes its scope
11 | #if true
12 | func intUTF8SpanCount3(_ i: Int) -> Int {
13 |     let span = String(i).utf8.span
   |         |                `- note: it depends on the lifetime of this parent value
   |         `- error: lifetime-dependent variable 'span' escapes its scope
14 |     return span.count
   |                 `- note: this use of the lifetime-dependent value is out of scope
15 | }
16 | #endif
Compiler returned: 1

Expected behavior

The first two should also produce an escape diagnostic.

Environment

swift-DEVELOPMENT-SNAPSHOT-2025-06-03-a

Code example: https://swift.godbolt.org/z/zxo6b358f

Additional information

Related to: #81931
Also tracked as: rdar://152660149

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.ownershipFeature: Ownership modifiers and semantics

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions