Home > Software engineering >  How to change properties of all set elements in Swift
How to change properties of all set elements in Swift

Time:10-23

enum Posts {
case roxham
case satellite
case zone34
}

struct Member: Hashable, Identifiable {
    var name: String
    var permanent: Bool
    var shift: Shifts
    var post: Posts?
    var canLedger = false
    let id = UUID()
}

let allMembers: Set<Member> = [Member(name: "Bob Smith", permanent: false, shift: .fiveAM),
                               Member(name: "Dave Johnson", permanent: false, shift: .sevenAM) 
                             // This set contains 15 more members ]

var tempSet = Set<Member>()

What I am trying to do is to assign .satellite to the post property of each element of the allMembers set and then put them into the tempSet Set (or put them in tempSet first then change the property, doesn’matter). I have tried mapping but the fact that I’m using a struct makes it impossible. I have also attempted some loops but with the same result. Of note, I have many more members in allMembers, I only showed 2 for simplification purposes. I obviously know I can just write it in manually in allMembers, however I will have to this a lot throughout the code and the sets will become much larger. Thanks

CodePudding user response:

How about:

let tempSet = Set<Member>(allMembers.map {
            var temp = $0
            temp.post = .satellite
            return temp
        })
  • Related