Firstly, I was using xcode version 13.2.1 and I have a problem when trying to build my ios App in terminal / xcode, here is the error response :
/Users/user/.pubcache/hosted/pub.dev/shared_preferences_foundation-2.3.0/ios/Classes/SharedPreferencesPlugin.swift:58:22: Variable binding in a condition requires an initializer
and here is the full function that get error :
func getAllPrefs(prefix: String, allowList: [String]?) -> [String: Any] {
var filteredPrefs: [String: Any] = [:]
var allowSet: Set<String>?;
if let allowList {
allowSet = Set(allowList)
}
if let appDomain = Bundle.main.bundleIdentifier,
let prefs = UserDefaults.standard.persistentDomain(forName: appDomain)
{
for (key, value) in prefs where (key.hasPrefix(prefix) && (allowSet == nil || allowSet!.contains(key))) {
filteredPrefs[key] = value
}
}
return filteredPrefs
}
and the error comes from this specific function :
if let allowList {
allowSet = Set(allowList)
}
I never use if let function, so I don’t know how to solve this swift error.
Can someone tell me how can I solved this?
2
Answers
Apparently this has been fixed in newer versions of swift but here I would replace the
if
withor perhaps even better
and a third option 🙂
You are trying to use the feature "
if let
shorthand for shadowing an existing optional variable". This is implemented in Swift 5.7. The Xcode version you are using – 13.2 – only supports Swift 5.5.2. See: https://swiftversion.net/The lowest Xcode version that supports Swift 5.7 is 14.0. You can update to that version to fix the error.
You can also rewrite the code. In addition to Joakim Danielson’s suggestions, you can also do: