[swift-evolution] [Discussion] Updating Struct Values While Looping

Paul Ossenbruggen possen at gmail.com
Mon Mar 7 02:57:37 CST 2016


So I have some code that utilizes structs, I would like to go through and update some of the values. While I could use map, it seems I should be able to do it using a for in loop without utilizing indexes. The mutate2 method uses enumerate, and the index to write back the copy to the array, but I would prefer to update the struct value itself and avoid having to use indexes as I try to avoid them, if possible.. It seems the structs kind of force you to go back to indexes. I was thinking that it would be useful to be able to apply the & (reference) operator here to allow direct access to the array element struct, an example of this is shown in mutate3. With a class this is not necessary. I know a little like C++ but just want to explore this idea unless there is some other way I missed. 

struct Codon {
    var val = Float(0.0)
    var mask = false
}

class Geno {
    var codons : [Codon]

    // pure index based approach
    func mutate() {
        for i in 0..<codons.count {
            if !codons[i].mask {
                codons[i].val += r.gauss() * vari
            }
        }
    }

    // index to write back, less efficient? 
    func mutate2() {
        for (index, var codon) in codons.enumerate() {
            if !codon.mask {
                codon.val += r.gauss()
                codons[index] = codon
            }
        }
    }  

    // suggested reference approach  
    func mutate3() {
        for var &codon in codons {
            if !codon.mask {
                codon.val += r.gauss()
            }
        }
    }
}

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160307/3eab75bd/attachment.html>


More information about the swift-evolution mailing list