I'm confused about why I am getting this error (swift 4.2.1).
// next, select only entries in range
let filteredDataOpt: [TimeSeriesEntry?] = filteredApps
.map { data in
let isInDate = dates.contains { date in
guard let d = date else {
return false
}
return Calendar.current.isDate(d, equalTo: data.date, toGranularity: Calendar.Component.day)
}
return isInDate ? timeSeriesDataFromAppData(data) : nil
}.append(contentsOf: locationsData.map { data in
let isInDate = dates.contains { date in
guard let d = date else {
return false
}
return Calendar.current.isDate(d, equalTo: data.date, toGranularity: Calendar.Component.day)
}
return isInDate ? timeSeriesDataFromLocationData(data) : nil
})
This produces
Cannot use mutating member on immutable value: function call returns immutable value
on the third line.
But this doesn't:
// next, select only entries in range
let filteredDataOpt: [AppData?] = filteredByApps
.map { data in
let isInDate = dates.contains { date in
guard let d = date else {
return false
}
return Calendar.current.isDate(d, equalTo: data.date, toGranularity: Calendar.Component.day)
}
return isInDate ? data : nil
}
let filteredData: [AppData] = filteredDataOpt.compactMap { $0 }
My confusion stems from the fact that I am manipulating a sequence with append rather than first assigning it to a constant and then appending to it. Why is my sequence read-only?
edit: apparently map is always (And at first glance at least, bizarrely) returning a constant. In full, my solution is just:
var filteredDataOpt: [TimeSeriesEntry?] = filteredApps
.map { data in
let isInDate = dates.contains { date in
guard let d = date else {
return false
}
return Calendar.current.isDate(d, equalTo: data.date, toGranularity: Calendar.Component.day)
}
return isInDate ? self.timeSeriesData(appData: data) : nil
}
filteredDataOpt.append(contentsOf: self.locationsData.map { data in
let isInDate = dates.contains { date in
guard let d = date else {
return false
}
return Calendar.current.isDate(d, equalTo: data.date, toGranularity: Calendar.Component.day)
}
return isInDate ? self.timeSeriesData(locationData: data) : nil
})
let filteredData = filteredDataOpt.compactMap { $0 }
But, does anyone else find that unsatisfactory? I'm stuck with:
- intermediate variables
- variables where what I need is just a constant
apparently map is always (And at first glance at least, bizarrely) returning a constant— mutability is not property of the value itself, but of it's "binding" (variable or constant); map returns just a "unbound" value. - user28434'mstep[1, 2].map({$0 * 2}).append(6)- vacawama