I encountered some strange behaviour of tuples with specified element names in combination with the reduce operator.
The following code (a simplified version of a real world section of my code) causes a runtime crash, no compiler errors or warnings given.
// Define some data using tuples with element names
let myData: [[(id: Int, data: String)]] = [[(100,"Apple"),(200,"Orange")], [(300,"Lemon")]]
//I use the reduce function to flatten the array and misspelled one element name.
//This will compile just fine, but causes a runtime crash
let myFlatData1: [(id: Int, daata: String)] = myData.reduce() {$0 + $1}
//The same code with type annotations to make it clear what happens.
// The compiler should detect that “item” has the wrong type - i.e. (id: Int, data: String)
let myFlatData2: [(id: Int, daata: String)] = myData.reduce((id: Int, daata: String)) {
(accumulator: [(id: Int, daata: String)], item: [(id: Int, daata: String)]) in
accumulator + item
//I could of course used flatMap (which I probably should have), but I didn’t. flatMap behaves as expected, the following code will not compile.
let myFlatData3: [(id: Int, daata: String)] = myData.flatMap{$0}
If I’m not completely mistaken, I think it is a pretty serious bug since a simple misspelling could lead to unexpected crashes. I’m looking forward to hearing any thoughts on this from the community.
Kind regards,
Anders