/errors/swift/cannot-find-in-scope
Swift error: cannot find 'x' in scope
- 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:
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):
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 scopeWhen 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 found | Fix |
|---|---|
| A typo or wrong case | Correct it; Xcode offers a fix-it with the similar name |
| A variable declared inside if, guard, do or a closure | Declare 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 package | import the module, and add the product to the target dependencies |
| A type in another file of the same app | Check Target Membership of that file in Xcode |
| A private or fileprivate declaration in another file | Use 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:
.executableTarget(
name: "App",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
]
)Sources
- docs.swift.orgdocs.swift.org/swift-book/documentation/the-swift-programming-language/accesscontrol
- docs.swift.orgdocs.swift.org/swift-book/documentation/the-swift-programming-language/thebasics
- swift.orgwww.swift.org/documentation/package-manager/
- developer.apple.comdeveloper.apple.com/documentation/xcode/adding-package-dependencies-to-your-app