swift2 - Array mutability in Swift -
according apple's swift guide:
if create array, set, or dictionary, , assign variable, collection created mutable. means can change (or mutate) collection after created adding, removing, or changing items in collection. if assign array, set, or dictionary constant, collection immutable, , size , contents cannot changed.
but in xcode 7.2.1, these results:
import foundation //**added per comments** var data: [int] = [10, 20] print(unsafeaddressof(data)) data.append(30) print(data) print(unsafeaddressof(data)) --output:-- 0x00007ff9a3e176a0 [10, 20, 30] 0x00007ff9a3e1d310
because assigned array var
, expected see same address data after appending value data.
another example:
class item { } var data: [item] = [item(), item()] print(unsafeaddressof(data)) data.append(item()) print(data) print(unsafeaddressof(data)) --output:-- 0x00007f86a941b090 [item, item, item] 0x00007f86a961f4c0
and another:
var data: [string] = ["a", "b"] print(unsafeaddressof(data)) data[0] = "a" print(data) print(unsafeaddressof(data)) --output:-- 0x00007faa6b624690 ["a", "b"] 0x00007faa6b704840
first of all, example compiles if has import foundation
@ top. because without array
structure not conform anyobject
protocol used in unsafeaddressof(object: anyobject)
signature. read more here:
instances of swift string structure type cannot represented anyobject type, because anyobject represents instances of class type. however, when bridging foundation enabled, swift string values can assigned constants , variables of anyobject type bridged instances of nsstring class.
that's true arrays (array
bridged nsarray
), sets (set
bridged nsset
), dictionaries (dictionary
bridged nsdictionary
) , numbers (int
, uint
, float
, double
, bool
bridged nsnumber
).
so every time call unsafeaddressof(data)
data structure implicitly bridged unique nsarray
object , because of see different address each time. if not mutate structure between calls unsafeaddressof()
bridged nsarray
object can same. think that's because of optimization.
try code in playground:
import foundation func printdata(data: anyobject) { //print(data) // uncomment see data value print(unsafeaddressof(data)) } var data = [10, 20] printdata(data) data.append(30) printdata(data) var nsarray = data nsarray printdata(nsarray)
run several times , you'll see 2 last printed addresses same , it's not.
in general question not relate mutability of value types. see happens because swift value types bridged foundation
reference types.
Comments
Post a Comment