[SR-2730] Failure to initialize global variable
| Previous ID | SR-2730 |
| Radar | None |
| Original Reporter | @jadengeller |
| Type | Bug |
| Status | Resolved |
| Resolution | Duplicate |
Environment
Swift 3
Additional Detail from JIRA
| Votes | 0 |
| Component/s | Compiler |
| Labels | Bug |
| Assignee | None |
| Priority | Medium |
md5: 61eabde96dfa157dcf6729f925cf4571
duplicates:
- SR-2727 Script mode rules for top-level bindings are confusing and broken
Issue Description:
The following code snippet successful compiles and runs without infinite looping.
func foo() -> Int {
return x
}
let x = foo()
It seems that `x` is uninitialized when returned from `foo` so `x` is assigned to an uninitiated value. In this example, printing `x` will output `0`, but if we change `Int` to a more complicated type like `[Int]`, printing will crash the program for obvious reasons.
I would expect this code to not compile since `x` is declared after `foo`. If it is intended to compile, then I think it ought to infinite loop. I definitely think the former behavior is much more intuitive than the latter.
Sounds like the behavior can differ when `x` is used across file boundaries. https://twitter.com/bitCycle/status/778731158007709696
Possibly related example:
This little Swift program compiles (and runs) fine:
func foo() -> Int { return a }
let a = 1
let b = 2
print(foo())
But if `foo()` returns `b` instead of `a`, we get the compile time error:
"Use of unresolved identifier `b`"
If this is the intended behavior, I would argue that it violates the principle of least surprise.
Also possibly related to: https://bugs.swift.org/browse/SR-284
Yep.