Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Frozen in Swift

Tags:

swift

What does the qualifier "frozen" mean in Swift? I can take a guess but I cannot find any description in the help files or any other source.

Looked in the help files, on line and in stack overflow. Cannot find any reference but the term is used in Apple example code.

like image 811
OldPivot Avatar asked Nov 25 '25 09:11

OldPivot


1 Answers

@frozen is a Swift construct rather than a SwiftUI one.

In framework libraries, it's used to denote an enum that will not receive additional values in future. It can be used to determine whether any switch expressions in your code need to allow future values that aren't known right now.

For example, a color scheme enum might have two values now, but could have others added in future:

// in MyLibrary package
public enum ColorScheme {
  case light
  case dark
}

but an enum for a 2D axis might only ever have two values, in which case we could mark it as frozen:

// in  MyLibrary package
@frozen public enum Axis2D {
  case horizontal
  case vertical
}

When importing this library, is you do a switch on Axis2D, the compiler will want you to provide code for both horizontal and vertical cases. Once you have done this, the compiler will be happy.

However, in the case of ColorScheme, the compiler will try and protect you from future additions to the enum should a newer version of the library come to add one.

If you have explicit code to cover ColorScheme.light and ColorScheme.dark, there's nothing in your code that would account for a new third scheme - say ColorScheme.solarized.

If you add a default: case, the compiler will grumble because that code will never be executed in its current form. Instead you mark it as @unknown default: to let the compiler know that it's just to catch future possible cases:

import MyLibrary
import SwiftUI

var textColor: Color {
  switch colorScheme {
    case .light: return .white
    case .dark: return .black
    @unknown default: return .red
  }
}

If you already have a default case which already matches an existing value can be used for any new additions, you don't need the @unknown marker:

switch colorScheme {
  case .light: return .white
  default: return .black // covers ColorScheme.dark and any new enum values
}

Note that if you're defining enums in your own codebase, you don't need to mark them @frozen or otherwise; the Swift compiler knows that if you're using your own enums, all current cases must be covered and any new cases you add will automatically be compiler issues. Thus, @frozen is only useful if you're creating a package to be used by other Swift code.

like image 190
Scott Matthewman Avatar answered Nov 27 '25 22:11

Scott Matthewman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!