0

I'm trying to use the brand new Swift Chart framework, and the chartForegroundStyleScale function takes a KeyValuePairs as the argument. I tried supplying a Dictionary (of [String:Color], but I get the error Cannot convert value of type '[String : Color]' to expected argument type 'KeyValuePairs<DataValue, S>'.

Ok so fair enough, I need to convert the Dictionary to a KeyValuePair. I tried creating the KVP the same way I created the Dictionary, but this doesn't work. I loop through the appropriate array and build a dictionary, but this doesn't work with a KVP as you cannot modify a KVP once it's created. I also need to add around 40 Keys and Pairs to the item, not a single one.

I tried creating a KVP from the dictionary like this

 let myKVP = KeyValuePairs(dictionaryLiteral: myDictionary)

But this fails with the error Cannot convert value of type '[String : Color]' to expected argument type '(Key, Value)'

All the tutorials I find involve typing out and hard coding the KVP data, which isn't possible for me, as the data will be different each time the app opens. So how do I generate a KVP?

Claus Jørgensen
  • 25,882
  • 9
  • 87
  • 150
dsellis
  • 3
  • 5
  • You can’t. There is no way to use a dictionary to instantiate a KeyValuePair – Leo Dabus Nov 19 '22 at 19:55
  • Unfortunately the only way to generate a KVP is using a dictionary literal. – Leo Dabus Nov 19 '22 at 19:59
  • @LeoDabus So is there an industry accepted way of creating a KVP dynamically? I can make this work if I hardcode the data, but I don't know how to generate the KeyValurePairs from programmatically from the downloaded data. – dsellis Nov 19 '22 at 20:13
  • @JoakimDanielson This answer is for entering data into a chart, for not styling it. – dsellis Nov 20 '22 at 09:59
  • @ClausJørgensen This may be the answer. I'll mark it as correct. – dsellis Nov 20 '22 at 10:00
  • @JoakimDanielson you're missing the point, you can't pass tuples to `chartForegroundStyleScale` , that's the key problem here. Also if you wanted to just suggest tuples maybe just link to the Swift documentation on Tuples, not a unrelated question for a unrelated function taking a unrelated type. – Claus Jørgensen Nov 20 '22 at 15:17

0 Answers0