Three questions about circular reference

Hello forum,

I got 3 questions about circular reference. Thanks!

Circular reference - 1
Build Failed

//main.swift
print(a,b)
//a.swift
var a = b //global
//b.swift
var b = a

Circular reference - 2
Runtime Failed. When it's with type annotations. Why?

//main.swift
print(a,b)
//a.swift
var a: Int = b //global. with type annotation
//b.swift
var b: Int = a

Circular reference - 3

//main.swift
var a = a //Build Failed
var a: Int = a //it's Ok with type annotation, Why?
  1. It fails because the compiler cannot infer the type of a or b. At least one of them needs a type annotation.

  2. It fails because your definitions of a and b are mutually recursive.

  3. It doesn't fail because you have declared two different variables called a. The second one "shadows" the first, which is legal in Swift (though confusing in this example).

    For the first a, the compiler gives an error because it doesn't have a valid initial value.

    For the second a, the compiler is a bit forgiving. It "knows" that there is an earlier a that can be used to initialize the second a, once you give the first one a valid initialization value, so there's no point in having a second error message here.

2 Likes

This is not legal in swift. A variable cannot shadow another variable in the same scope:

var a = 5
var a = 10  // Invalid redeclaration of 'a' 

There is one exception, though: shadowing a function argument label:

func function(a: Int) {
    var a = 5
}

I'm not even sure that's an exception.The arguments are all defined before the opening brace of the function's scope.

Terms of Service

Privacy Policy

Cookie Policy