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

Dmitri Gribenko gribozavr at gmail.com
Mon Mar 7 04:34:28 CST 2016


On Mon, Mar 7, 2016 at 2:24 AM, Dmitri Gribenko <gribozavr at gmail.com> wrote:
> On Mon, Mar 7, 2016 at 12:57 AM, Paul Ossenbruggen via swift-evolution
> <swift-evolution at swift.org> wrote:
>>     func mutate3() {
>>         for var &codon in codons {
>>             if !codon.mask {
>>                 codon.val += r.gauss()
>>             }
>>         }
>>     }
>> }
>
> This would be a useful extension to the language (but it is not clear
> how to define it -- do we need to hardcode the knowledge about the
> MutableCollection protocol into the compiler?)
>
> There's something you can do today, though:
>
> extension MutableCollectionType {
>   public mutating func mutatingEach(mutate: (inout Generator.Element) -> Void) {

This method should be called 'mutateEach' to conform to the guidelines, though.

Dmitri

>     for i in self.indices {
>       mutate(&self[i])
>     }
>   }
> }
>
> var a = [1,2,3]
> a.mutatingEach { (x: inout Int) -> Void in x += 1 }
> //a.mutatingEach { $0 += 1 } // does not work, probably due to a compiler bug.
> print(a)
>
> Dmitri
>
> --
> main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
> (j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/



-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/


More information about the swift-evolution mailing list