Do local private "global" values get released from memory?

Let's say I have the following in a file:

import SwiftUI

struct MobyDickView: View {
  var body: some View {
    Text(mobyDick)
  }  
}

private let mobyDick: String = """
Call me Ishmael. Some years ago--never mind how long precisely[...]
"""

Does mobyDick ever get released from memory if, for example, MobyDickView isn't being used otherwise? Does this change if the string is instead:

private extension String {
  static let mobyDick: String = """
  [...]
  """
}

or

private extension String {
  static var mobyDick: String {
    """
    [...]
    """
  }
}

or

private var mobyDick: String {
  """
  Call me Ishmael. Some years ago--never mind how long precisely[...]
  """
}

?

Global and static variables persist for the lifetime of the process after they get initialized. If you define them as a computed property instead, then a value will be created and returned locally every time the getter is invoked, and would get released when that value is no longer used. With constant strings, like in your examples, there isn't that much of a difference, since the string will be emitted as a constant and the String value will just be a pointer to that global constant.

4 Likes