swiftfor-loop

For loop appending for each cycle at start rather than just once through its iteration


I am trying to get the key/values appended to some arrays once each. So my result should be a singular occurrence of each key/value pair in my array. However, after each iteration the key/value pair is added and then the iteration restart back at the beginning again, adding the key/value pair again each time.

How can I make it only append each key/value pair once?

import UIKit
import PlaygroundSupport

var usernameScoreDict : [String:String] = ["erer":"eree", "veev":"veve", "tbtt":"bttbt", "umum":"muumu", "bvbv":"bbbcb"]

var unArray = [String]()
var hsArray = [String]()

class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        usernameScoreDict.forEach { (key,value) in
            print("key is - \(key) and value is - \(value)")
            unArray.append(key)
            hsArray.append(value)
        }
    }
}

Solution

  • Iterating Through Dictionary and Removing Duplicates from Arrays in Swift

    You can achieve this in Swift using a combination of dictionary iteration and array manipulation. Here's a step-by-step approach:

    Step 1: Iterate through the dictionary

    To iterate through a dictionary and append its keys and values to separate arrays, you can use a for-in loop with tuple decomposition:

    let usernameScoreDict = ["Alice": 100, "Bob": 85, "Charlie": 90, "Alice": 95]
    var unArray: [String] = []
    var hsArray: [Int] = []
    
    for (key, value) in usernameScoreDict {
        unArray.append(key)
        hsArray.append(value)
    }
    

    After this step:

    Note: In this example, the second "Alice" entry overwrites the first one in the dictionary, as dictionaries can't have duplicate keys.

    Step 2: Remove duplicates (if necessary)

    If you want to ensure there are no duplicates in your arrays (which is unlikely for the keys array as dictionary keys are unique, but possible for the values array), you can use Set:

    unArray = Array(Set(unArray))
    hsArray = Array(Set(hsArray))
    

    This operation will remove any duplicates while potentially changing the order of elements.

    Important Considerations

    1. Dictionary Keys: Dictionary keys are unique by definition, so unArray will never have duplicates unless you're appending keys from multiple dictionaries.

    2. Order: Using Set to remove duplicates will not preserve the original order of elements. If order is important, you'll need a different approach.

    3. Value Types: This method works for arrays of Hashable types (like String and Int). For custom types, ensure they conform to Hashable.

    4. Efficiency: Converting to Set and back to Array is O(n) operation. For large datasets, consider alternative approaches if performance is critical.

    Alternative Approach for Maintaining Order

    If you need to maintain the order while removing duplicates, you can use this approach:

    extension Sequence where Element: Hashable {
        func uniqued() -> [Element] {
            var set = Set<Element>()
            return filter { set.insert($0).inserted }
        }
    }
    
    unArray = unArray.uniqued()
    hsArray = hsArray.uniqued()
    

    This method preserves the original order while removing duplicates.

    Conclusion

    The provided solution offers a straightforward way to iterate through a dictionary and optionally remove duplicates from the resulting arrays. However, it's important to consider the specific requirements of your use case, especially regarding the preservation of order and the handling of the dictionary's unique keys.