skip to Main Content

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?

2

Answers


  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!)
    
    Login or Signup to reply.
  2. 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) ?? []
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search