i'm trying reference array
, make modifications it. because array
s in swift value types, instead of reference types, if assign array variable first, getting copy of array instead of actual array:
var odds = ["1", "3", "5"] var evens = ["2", "4", "6"] var source = odds var destination = evens var 1 = odds.first! source.removefirst() // removes first element of `source` array, not `odds` array destination.append(one)
when @ odds
, evens
arrays, unaltered because changed source
, destination
arrays.
i know can use inout
parameter attribute on function pass them reference, instead of value:
func move(inout source: [string], inout destination: [string], value:string) { source.removeatindex(source.indexof(value)!) destination.append(value) } move(&odds, destination: &evens, value:one)
is there way assign these arrays variable reference, instead of value?
array
struct, means it's value type in swift. because of this, arrays behave according value , not reference semantics. problem here you're attempting use mutable, reference based logic operate on values types.
you don't want rely on mutations occurring inside function propagate caller. you've found, possible inout parameters. should instead return mutated array function caller. point of value oriented programming shouldn't matter which array have, rather 2 equivalent arrays or values types interchangeable.
it's easier imagine value type. take int example, , function math.
func addfive(int: int) -> int { return int + 5 }
now consider similar function, written in reference oriented style you're attempting use:
func addfive(inout int: int) { int = int + 5 }
you can see it's not natural operate on value types way. instead return updated value (the modified arrays) function , carry on there.
here function refactored value semantics.
func move(source: [string], destination: [string], value:string) -> ([string], [string]) { var mutablesource = source var mutabledestination = destination mutablesource.removeatindex(source.indexof(value)!) mutabledestination.append(value) return (mutablesource, mutabledestination) } let (updatedsource, updateddestination) = move(odds, destination: evens, value:one)
Comments
Post a Comment