Skip to content

/errors/swift/cannot-find-in-scope

Swift error: cannot find 'x' in scope

The commands on this page have not been executed by our verification runner yet.updated
tool
Swift
exit code
1
versions
Swift 5.3+ (earlier versions said use of unresolved identifier)
os
macos, linux, windows

error: cannot find 'x' in scope means the Swift compiler found no variable, function, type or constant named x that is visible at that point. The usual causes are a typo, a declaration that lives in an inner scope (inside an if, guard or closure), a missing import, or a file or package that is not part of the target being built. Since Swift 5.3 this message replaced the older use of unresolved identifier 'x'; type names report the variant cannot find type 'X' in scope.

What it looks like

The diagnostic text comes from the Swift compiler's cannot_find_in_scope and cannot_find_type_in_scope diagnostics. For a file like this:

main.swift
let name = "Ada"
print(total)

if true {
    let greeting = "Hello"
}
print(greeting)

let formatter = DateFormatter()

swiftc main.swift reports each unknown name with its location, in the file:line:column: error: format (warnings omitted):

text
main.swift:2:7: error: cannot find 'total' in scope
main.swift:7:7: error: cannot find 'greeting' in scope
main.swift:9:17: error: cannot find 'DateFormatter' in scope

When a declaration with a similar name exists, the compiler appends a suggestion: cannot find 'x' in scope; did you mean 'y'?. DateFormatter is part of Foundation, so the third error disappears after import Foundation.

Where to look

Name that is not foundFix
A typo or wrong caseCorrect it; Xcode offers a fix-it with the similar name
A variable declared inside if, guard, do or a closureDeclare it before the block, or use it inside the block
A Foundation or UIKit type (URL, Date, UIColor)import Foundation or import UIKit at the top of the file
A type from a Swift packageimport the module, and add the product to the target dependencies
A type in another file of the same appCheck Target Membership of that file in Xcode
A private or fileprivate declaration in another fileUse internal (the default) or a wider access level
Code under #if DEBUG or #if os(iOS)Build with the matching configuration or platform

A package target that uses another package's product must list it:

Package.swift
.executableTarget(
    name: "App",
    dependencies: [
        .product(name: "ArgumentParser", package: "swift-argument-parser"),
    ]
)

Sources