Global Scope in Swift
Image via Author

Global Scope in Swift

In Swift, declarations such as variables, constants or functions declared at the top level of a file, exist within the global scope. Such global entities are accessible from anywhere within the same file or module, depending on their access control level.

This is in direct contrast to block-level scope where the entities declared only exist within the block and cannot be accessed beyond the closing curly brace.

In the following example, there are two variable declarations. The first is declared at top-level and the second is block-level.


var studentName = "Estelle"

func mathClass() {
    
    print("\(studentName) is in this Math class") // prints Estelle is in this Math class
    
    var classPresident = "Arnold"
    
    print("\(classPresident) is in this Math class") // prints Arnold is in this Math class
}

print(classPresident) // error: cannot find 'classPresident' in scope

mathClass()        


Although studentName is declared at a global level, it is visible and accessible to the mathClass() function.

The classPresident variable can only be used inside of the block where it was declared and attempting to print it outside of the block gives an error stating that it “cannot find ‘classPresident’ in scope.”

The advantage of Swift global variables is that they are accessible everywhere in the app, however, it’s generally best practice to limit their use to only when necessary as they can introduce convoluted bugs within your applications if not properly managed.

Lastly, it’s worth noting that the default behaviour of global-level declarations can be overridden through Swift’s Access Modifiers. We’ll cover this topic in a later post.

要查看或添加评论,请登录

Ijeoma Nelson的更多文章

社区洞察

其他会员也浏览了