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?

2
  • 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 Commented Jul 6, 2023 at 7:28
  • @JoakimDanielson I edit my post with picture of the error, if you get that error too. How do you analyze that problem? Commented Jul 6, 2023 at 7:33

2 Answers 2

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!)
Sign up to request clarification or add additional context in comments.

Comments

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) ?? []

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.