ios – Swift: adding a new value to an Encodable object

0
31

[ad_1]

I can’t find a clue to add a new value to an Encodable object and then return the result as Encodable object again, as follows:

func add(pageNumber: Int, toParams params: Encodable? = nil) -> Encodable {
        
        var parameters: [String: Any] = [:]
        
        if let params = params {
            
            let jsonEncoder = JSONEncoder()
            
            if let jsonData = try? jsonEncoder.encode(params),
               
                let jsonObject = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                
                parameters = jsonObject
                
            }
            
        }
        
        parameters["page"] = pageNumber
        
        return parameters
    }

I need the input params to be Encodable (as in the code snippet above) and not [String:Any] as it may hold objects of different types, one of them and not limited to, is a [String:Any] dictionary.

And in case there’re no input params to the function, it should return an Encodable [String: Any] dictionary that holds pageNumber.

[ad_2]