I want to sort the dictionary and then convert it into an array, but I get an error with the code below.
Commenting out the line self.cards=sortedDic.map{$0.value}
produces a similar error, but the sorted(by:<)
has been used elsewhere and works fine.
error message
Command failed due to signal:Illegal instruction:4
source code
funceditDictionaryData(data:[Int:CardItem]){
let sortedDic=data.sorted (by:<)
self.cards = sortedDic.map {$0.value}
}
I thought it was an xcode bug, so
cmd+shift+k
cmd+shift+option+k
I tried the xcode reboot, but it didn't work.
I tried both xcode 11.6 and 11.5.
Can someone please teach me?
swift xcode
After writing the comment, I noticed that the title clearly states "Sort the dictionary by key" and that there are some things I can write as answers.
First, the sorted(by:)
closure of the Swift type Dictionary
must receive the arguments ((key:Int,value:CardItem),(key:Int,value:CardItem))
.There are two arguments, both of which are tuples containing key
, value
.
sorted(by:<)
Compare between these tuples for successful calls
(key:Int,value:CardItem)<(key:Int,value:CardItem)
must be defined in some way.
Swift automatically defines comparison operations between tuples <
depending on the type of tuple element, so sorted(by:<)
succeeds only in such cases.In this case, it seems that such conditions have not been met.
(Originally, an error message should be issued that means "no such operation is defined" even if it is not successful.If you have time, Apple's feedback assistant should send you a bug report.)
However, in this question, you want to sort the dictionary by key, so comparing the entire tuple, including both key-value, is doing something different from what you want to do.(key
is ahead, so the result will be as expected.)
If you want to sort by key, try explicitly comparing the key
to each other.
let sortedDic=data.sorted {$0.key<$1.key}
This should at least prevent the compiler from stopping at Illegal instruction:4.
© 2024 OneMinuteCode. All rights reserved.