Looking for swift Answers? Try Ask4KnowledgeBase
Looking for swift Keywords? Try Ask4Keywords

Swift Language Local and Global Variables


Local variables are defined within a function, method, or closure:

func printSomething() {
    let localString = "I'm local!"

func printSomethingAgain() {
    print(localString) // error

Global variables are defined outside of a function, method, or closure, and are not defined within a type (think outside of all brackets). They can be used anywhere:

let globalString = "I'm global!"

func useGlobalString() {
    print(globalString) // works!

for i in 0..<2 {
    print(globalString) // works!

class GlobalStringUser {
    var computeGlobalString {
        return globalString // works!

Global variables are defined lazily (see "Lazy Properties" example).