koen
koen

Reputation: 5729

Use map to change struct property into new array

I am trying to create a new array from another array with some property changed. I followed the answer in this thread: Using Map in Swift to Change Custom Struct Properties, but I am not getting it to work, and get a crash in my PlayGround (XCode 8beta6)

Here is a simple example:

struct Day {
   var day: String
}

var mondays: [Day] = []

for i in 0..<10 {
   let day = Day(day: "Monday")

   mondays.append(day)
}

print(mondays)

// create a new array where all days have the day property set to 'Tuesday'
let tuesdays = mondays.map { (var d) -> Day in
   d.day = "Tuesday"
   return d
}

print(tuesdays)

Once I add the second part of the code I get a crash, with a long crashlog (which I will not reproduce here since it's too big). So it could just be a bug in Swift 3 and/or Xcode beta.

My question is, is there an error in my code, am I using the map correctly?

Upvotes: 0

Views: 995

Answers (1)

Hamish
Hamish

Reputation: 80821

As per SE-0003, var function parameters have been removed from Swift 3 (also see this Q&A on the topic). The fact that the compiler crashes instead of generating an error message telling you this, is a bug – the compiler should never crash.

The solution is simply to simply create your own mutable copy of map(_:)'s function parameter.

let tuesdays = mondays.map { (d) -> Day in
    var d = d // mutable copy of d that shadows the immutable function argument d
    d.day = "Tuesday"
    return d
}

Upvotes: 6

Related Questions