Why?

I wrote an app that users can create utilities using terminal commands

I'm experiencing a bug that's driving me crazy:

I have an array of utilities, and by extension, I made Array<Utility> and Utility RawRepresantable:

Part of the declaration for Utility

public init?(rawValue: String) {
    guard let data = rawValue.data(using: .utf8),
          let result = try? JSONDecoder().decode(Utility.self, from: data)
    else { return nil }
    self = result
}

public var rawValue: String {
    var encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    guard let data = try? encoder.encode(self),
          let result = String(data: data, encoding: .utf8)
    else {
        return ""
    }
    return result
}

extension for Array<Utility>

extension Array: RawRepresentable where Element: Codable {
    public init?(rawValue: String) {
        guard let data = rawValue.data(using: .utf8),
              let result = try? JSONDecoder().decode([Element].self, from: data)
        else { return nil }
        self = result
    }
    
    public var rawValue: String {
        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        guard let data = try? encoder.encode(self),
              let result = String(data: data, encoding: .utf8)
        else {
            return "[]"
        }
        return result
    }
}

And now, because of some strange SwiftUI bug (FB11401294) When I pass a binding down a view hierarchy such as List or ForEach they update weirdly. I implement an "edit" feature for my utilities so I will not directly use binding but to call a function that takes an inout of Array<Utility>, the original item, and the item after being edited:

func replace(_ sequence: inout [Utility], item: Utility, with replace: Utility) {
    var raw = sequence.rawValue
    print(raw)
    let rawReplaced = raw.replacingOccurrences(of: item.rawValue, with: replace.rawValue)
    print(item.rawValue, replace.rawValue)
    print(rawReplaced)
    sequence = [Utility].init(rawValue: sequence.rawValue.replacingOccurrences(of: item.rawValue, with: replace.rawValue))!
    print(sequence)
}

And the problem is it works

and after implementing another completely different feature it stopped working

from my debugging, the input of the function is correct and the problem is inside the function. But, as the error seems to be on this line:

sequence = [Utility].init(rawValue: sequence.rawValue.replacingOccurrences(of: item.rawValue, with: replace.rawValue))!

Now i have completely no idea why this works last time and won't now

This line of code works completely well in playgrounds and is now freaking me out

Help anyone?

Answered by makabaka1880 in 730551022

Found out why

In my Utility the variable id will be generated everytime it's accessed

Accepted Answer

Found out why

In my Utility the variable id will be generated everytime it's accessed

Why?
 
 
Q