Home>

A question about how to name Swiftvariable(→ constant) names.

let a: Int? = 123
if let a: Int = 123 {
    print (a)
}
print (a)

Running the above, the result is
123
Optional (123)
have become.

In other words, even if there is avariable(→ constant) a of type Int? Does that mean that Int type a is used preferentially?

I'm probably misunderstood, so I'm looking forward to an answer that I can understand ...

p.s.
You can understand only that Optional (123) is because ofscale(→ scope) ofvariable(→ constant) a of Int type.

  • Answer # 1

    I thought it was interesting the moment I saw this question.

    Start with code

    let value: Int = 150
    class Shadowing {
        let value: Int? = 100
        init () {
            let value = value // Error
            if let value = value {
                print (value) //
                print (self.value)
            }
            print (value)
        }
    }

    In the example above, the Int? type constantvalueis the same as the constantvaluein the if-let syntax. Using the same name in this way is called shadowing (I know the name for the first time. I don't accept Tsukkomi who just wants to say shadowing).

    And the question

      

    Even if there is an Int? type variable a, you can declare a new Int type a in the if-let

    This is yes. However, the Int type a and the Int? Type a written in the question are constants, not variables. The variable isvar.

      In

    if, does it mean that Int type a is used preferentially?

    This is a constant a in the if-let syntax rather than priority. If it is self.a, it points to a of Int? type. This is also related to scope issues.

    There are almost no misunderstandings, so there is no problem with understanding.

    (Added)

    >>tyobigorou's comment is received and corrected.

    Swift can now be shadowed during optional binding. This can be done as an exception, and usually shadowing is not possible. Perhaps there is a way, but the result of my investigation was only during optional binding. I've heard that Swift is influenced by Haskell, and shadowing is possible in that Haskell. And Haskell seems to have a wider range of shadowing than Swift.
    The shadowing effect is that the assigned value cannot be used within a specific scope. So, in the above example, the value that is a member constant cannot be called directly in the block of the if-let syntax, and when the value is called, the constant value declared under the condition of the if-let syntax is called.

    Digress
    class Shadowing {
        let value: Int? = 100
        init () {
            if let value = value {
                print (value) // 100
                let value = 150
                print (value) // 150
                print (self.value) // Optional (100)
            }
            print (value) // Optional (100)
        }
    }

    For some reason this is allowed ...