0

I have a very simple project. It is Command Line Tool written on Swift 3.0 using Xcode 8.0. This program is:

import Foundation

func aaa() {
    print(a)
}

let a = "a"

aaa() 

This is working perfectly well and printing "a" in console, but lets do this program more complex:

import Foundation

func aaa() {
    print(a)
    print(b)
}

let a = "a"
let b = "b"

aaa()

And line

print(b)

is marked with error

Use of unresolved identifier 'b'

We can make even easier:

import Foundation

func aaa() {
    print(a)
}

aaa()

let a = "a"

And again, line

print(a)

is marked with error

Use of unresolved identifier 'a'

I am not newbie and I undertand that I can easily fix this error like putting all variables in the beginning of the program. Question is: why is it happening? I thought each file with extension .swift, it is a class and I can put variable and functions, call functions in any order (all variables and constants would be global)... And one last thing, I don't have ability to test this on Swift 2.2, but I don't remember I faced this bug before, so can it be a error of Swift 3.0 compiler? Thank you for any answer!

Alex
  • 1,038
  • 2
  • 12
  • 32

1 Answers1

0

It appears to be a Swift compiler error:

When I tested it with other variables:

enter image description here

It always skips first issue and complies at second variable, at first.

Generally, if wanted to access a variable, that's inside a function, and wanted to do any action with such a variable, it must be declared there.

I would follow this convention everywhere.

pedrouan
  • 12,762
  • 3
  • 58
  • 74
  • Thank you for answer. How do you think, should we report this to Apple? – Alex Sep 20 '16 at 10:33
  • Yes, why not? If you are lucky and if they reply you with different explanation, don't forget to share it here :) – pedrouan Sep 20 '16 at 10:43
  • I have reported this error to Apple, I do not why, they marked it as Duplicate. So, I think, I am not the first one who mentioned this. – Alex Jan 13 '18 at 13:53