@@ -65,6 +65,7 @@ enum AILog {
65
65
case decodedUnsupportedPartData = 3014
66
66
case codeExecutionResultUnrecognizedOutcome = 3015
67
67
case executableCodeUnrecognizedLanguage = 3016
68
+ case fallbackValueUsed = 3017
68
69
69
70
// SDK State Errors
70
71
case generateContentResponseNoCandidates = 4000
@@ -126,4 +127,32 @@ enum AILog {
126
127
static func additionalLoggingEnabled( ) -> Bool {
127
128
return ProcessInfo . processInfo. arguments. contains ( enableArgumentKey)
128
129
}
130
+
131
+ /// Returns the unwrapped optional value if non-nil or returns the fallback value and logs.
132
+ ///
133
+ /// This convenience method is intended for use in place of `optionalValue ?? fallbackValue` with
134
+ /// the addition of logging on use of the fallback value.
135
+ ///
136
+ /// - Parameters:
137
+ /// - optionalValue: The value to unwrap.
138
+ /// - fallbackValue: The fallback (default) value to return when `optionalValue` is `nil`.
139
+ /// - level: The logging level to use for fallback messages; defaults to
140
+ /// `FirebaseLoggerLevel.warning`.
141
+ /// - code: The message code to use for fallback messages; defaults to
142
+ /// `MessageCode.fallbackValueUsed`.
143
+ /// - caller: The name of the unwrapped value; defaults to the name of the computed property or
144
+ /// function name from which the unwrapping occurred.
145
+ static func safeUnwrap< T> ( _ optionalValue: T ? ,
146
+ fallback fallbackValue: T ,
147
+ level: FirebaseLoggerLevel = . warning,
148
+ code: MessageCode = . fallbackValueUsed,
149
+ caller: String = #function) -> T {
150
+ guard let unwrappedValue = optionalValue else {
151
+ AILog . log ( level: level, code: code, """
152
+ No value specified for ' \( caller) ' ( \( T . self) ); using fallback value ' \( fallbackValue) '.
153
+ """ )
154
+ return fallbackValue
155
+ }
156
+ return unwrappedValue
157
+ }
129
158
}
0 commit comments