1

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 :

enter image description here

/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?

  • I don't get any errors when building this code in a playground. _Edit_, building it online with an older compiler version (5.6) does generate the same error message – Joakim Danielson Jul 06 '23 at 07:28
  • @JoakimDanielson I edit my post with picture of the error, if you get that error too. How do you analyze that problem? – Dimas Satrya Jul 06 '23 at 07:33

2 Answers2

1

Apparently this has been fixed in newer versions of swift but here I would replace the if with

allowSet = allowList == nil ? [] : Set(allowList!)

or perhaps even better

var allowSet = Set<String>()

if allowList != nil {
    Set(allowList!)
}

and a third option :)

var allowSet = allowList == nil ? Set<String>() : Set(allowList!)
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
0

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:

var allowSet = allowList.map(Set.init) ?? []
Sweeper
  • 213,210
  • 22
  • 193
  • 313