Search code examples
swiftxcodeswift3

swift - why global static variable is not init?


Problem

  • Sometimes (maybe thread) kIndexMinID, kIndexMaxID value is 0

Code

// test.swift
let kIndexMinID :Int    = 100
let kIndexMaxID :Int    = 200

Question

  • Why not init value? (when init?)
  • How to global variable init ?

Status

  • Xcode 8.2.1
  • Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1)

Solution

  • It's highly recommended to encapsulate constants in structs

    struct Constants {
       static let kIndexMinID = 100
       static let kIndexMaxID = 200
    }
    

    The benefit (apart from the encapsulation) is that the constants are initialized lazily.