Search code examples
swifttypesinitialization

Which types initialise with default zero value when using a constructor in Swift?


Looking through a Swift MIDI library, I found a variable initialised like so:

var client = MIDIClientRef()

I only thought this was weird after realising that MIDIClientRef isn't a function, it's a typealias for a UInt32, so wondered why the constructor pattern is used.

So a few simple questions:

  • Is it common to initialise a variable like this: var myVar = Int()?
  • Which types initialise with a default zero value when initialised with a constructor like this?
  • How does it initialise with a zero value if no argument is passed in?

Looking at the public init() function in Swift.Math.Integers the comments state that it "Creates a new value equal to zero." But I couldn't find what actually creates this default value in the following code.


Solution

  • UInt32 conforms to the BinaryInteger protocol and that requires an init() method which “Creates a new value equal to zero.”

    There is also a default implementation which can be found in Integers.swift:

    extension BinaryInteger {
      /// Creates a new value equal to zero.
      @_transparent
      public init() {
        self = 0
      }
    
      // ...
    }
    

    Other types have explicit no-argument init methods, like all floating point types:

      @_transparent
      public init() {
        let zero: Int64 = 0
        self._value = Builtin.sitofp_Int64_FPIEEE${bits}(zero._value)
      }
    

    Examples:

    let d = Double()
    let f = Float()
    let c = CGFloat()
    

    Finally, all types which are imported from C have a default initializer in Swift that initializes all of the struct's fields to zero, as mentioned in the Xcode 6 release notes. Example (from Do I need to memset a C struct in Swift?):

    let hints = addrinfo()