Is it possible to make array reference immutable, but array content mutable? - swift

In Java, we can make an array reference immutable, and array content mutable, by using final keyword
Java
final int[] array = {1, 2, 3};
// Ok. Array content mutable.
array[0] = 9;
// Compiler error. Array reference immutable.
array = new int[]{4, 5, 6};
In Swift, they take one step further. Using let keyword, will make both array reference, and array content immutable.
Swift
let array = [1, 2, 3]
// Compiler error. Array content immutable.
array[0] = 9
// Compiler error. Array reference immutable.
array = [4, 5, 6]
In Swift, is it possible to make array reference immutable, but array content mutable?

The answer for your question is "yes" and "no", depends on what you have.
If you decide to declare a simple "let" constant, you can't modify it.
Why ? Because it prevents you to side effects (and you have some optimization).
For example if you just want to browse a list and print values, you don't modify the list.
myArray = [1,2,3]
for element in myArray {
print(element)
}
Why it can be cool ? Now if you know that you don't want to modify your list, it prevents you to use functions that can modify your list. It will save your time and avoid some behavior that you don't expect.
If you declare a var and you don't modify the value, Swift will tell you too.
Moreover, the concept of immutable in Swift is interesting if you use a struct or a class.
Imagine you have this structure and this class:
struct TestStruct {
var myInt: Int
init(myInt: Int) {
self.myInt = myInt
}
}
struct TestClass {
var myInt: Int
init(myInt: Int) {
self.myInt = myInt
}
}
In this structure you have myIntwhich is a var. What happens if you try to declare a TestStructure and a TestClass object with a let constant ?
let testStruct = Test(myInt: 3)
// Cannot assign to property: 'test' is a 'let' constant
test.myInt = 5
let testClass = Test(myInt: 3)
// It works
test.myInt = 5
In a struct, the let is propagated for every field, which is not the case for a class.

Using let keyword, will make both array reference, and array content immutable.
This isn't correct. There is no "array reference" here. An array is a value, just like an integer is a value. There is no "array reference." Variables can be let or var, but that doesn't change the nature of their value. You wouldn't say that var n = 4 made "4" mutable. Similarly, var ns = [1,2,3] doesn't make [1,2,3] mutable. It just means you can change what ns refers to. Calling ns.append(5) is just like n += 1. In each case they assign a new value. They don't mutate the old value.
As an implementation and optimization detail, it is possible that the underlying array storage that was used for ns will be mutated and used for the new ns value. But this is invisible to the caller. For example:
var array = [1,2] {
didSet { print("\(oldValue) -> \(array)") }
}
array.append(1)
array = [1,2,1]
// [1, 2] -> [1, 2, 1]
// [1, 2, 1] -> [1, 2, 1]
There's no deep difference between the append and the assignment. They are both assignments. And notice that setting the value to the same value is still just an assignment.
I'm harping on this because you can't just translate over a Java approach and have it work if your Java code relies on shared mutable state (where one part of the program modifies an array and others are supposed to have their reference update). But if your Java works that way, I recommend improving your Java to reduce its reliance on that. As long as you generally just pass values and return values, then it'll work exactly the same in Swift as in Java.
If you still need this kind of mutable array, then you can build one fairly easily by wrapping an Array in a class:
final class ArrayRef<Element>: MutableCollection, ExpressibleByArrayLiteral {
private var elements: [Element] = []
init(arrayLiteral elements: Element...) {
self.elements = elements
}
var startIndex: Int { elements.startIndex }
var endIndex: Int { elements.endIndex }
func index(after i: Int) -> Int { elements.index(after: i) }
subscript(position: Int) -> Element {
get { elements[position] }
set { elements[position] = newValue }
}
}
let array: ArrayRef = [1, 2, 3]
// Ok. "Array" content mutable.
array[0] = 9
// Compiler error. "Array" is immutable.
array = [4, 5, 6]
(This is a very simple and unoptimized implementation. With more work you can make it more efficient and improve the interface.)
But I don't particularly recommend this unless you really need it. There's a reason it doesn't exist in stdlib.

Related

A Constant Array's Items Can(Cannot) Be Modified If They Are Reference(Value) Types. Why?

Please have a look at the following code and note the compiler error on the last line:
class C {
var value: Int
init( _ value: Int) { self.value = value }
}
let array1 = [C(1), C(2), C(3)]
array1[0].value = 4
struct S {
var value: Int
}
let array2 = [S(value: 1), S(value: 2), S(value: 3)]
array2[0].value = 4 // Error: Cannot assign to property: 'array2' is a 'let' constant
From the compiler error I want to conclude that the item at index 0 is being read from array2, modified, and then written back to array2. What else could produce the result that there is an attempt to modify array2? But, if my reasoning is correct, then why does the same thing not happen with array1?
Classes Are Reference Types
Unlike value types(struct), reference types are not copied when they are assigned to a variable or constant, or when they are passed to a function. Rather than a copy, a reference to the same existing instance is used instead.
Please refer Apple documentation about Class & struct

In Swift, what are the semantics of subscripts yielding (or receiving) non-object types?

The Swift book does not clearly document the semantics of non-object types in conjunction with subscripts. The most obvious example is a Dictionary whose value type is an Array: Array is a struct. Therefore, when a subscript returns it, we should expect it to be copied. This, however, is very inconvenient. Fortunately, it seems also not to be the caseā€”at least not in Xcode 8.2.1 (Swift 3.1?).
Consider these examples:
var a: [Int] = [0] // [0]
var b = a // [0]
b.append(1)
b // [0, 1]
a // [0]
As we expect, the array a is copied when it is assigned to b. In contrast,
var h: [Int: [Int]] = [0: [0]] // [0: [0]]
h[0]!.append(1)
h[0] // [0, 1]
If the subscript were simply returning the value using ordinary semantics, we would expect that h[0] would still equal [0] after h[0]!.append(1), but in fact it is the array in the dictionary that is appended to. We can even see if we like that the value remains at the same location in memory, suggesting that it is semantically the same array that was appended to. (Being at the same location does not imply that, but it is not in conflict with that, either.)
var h: [Int: [Int]] = [0: [0]] // [0: [0]]
var aptr: UnsafePointer<[Int]>? = nil
withUnsafePointer(to: &h[0]!) { aptr = $0 }
aptr // UnsafePointer(0x7FFF5351C2C0)
h[0]!.append(1)
withUnsafePointer(to: &h[0]!) { aptr = $0 }
aptr // UnsafePointer(0x7FFF5351C2C0)
This fortunate but seemingly-undocumented behavior does not apply only to Arrays as Dictionary values.
struct S: CustomStringConvertible {
var i: Int = 0
var description: String { return "S(i=\(self.i))" }
}
var g: [Int: S] = [0: S()]
g[0]! // S(i=0)
g[0]!.i = 5
g[0]! // S(i=5)
And, in fact, it does not even apply only to the subscripts of Dictionary types.
struct T {
var s: S? = S()
subscript(x: Int) -> S? {
get {
return self.s
}
set(s) {
self.s = s
}
}
}
var t = T()
t[0]! // S(i=0)
var tptr: UnsafePointer<T>? = nil
withUnsafePointer(to: &t) { tptr = $0 }
tptr // UnsafePointer(0x1007F6DB8)
t[0]!.i = 5
t[0]! // S(i=5)
withUnsafePointer(to: &t) { tptr = $0 }
tptr // UnsafePointer(0x1007F6DB8)
Notably, this does somehow involve the setter: If the set under subscript is removed from the definition of T, the statement t[0]!.i = 5 produces the error
error: cannot assign to property: subscript is get-only
My preferred answer would be a pointer to some Swift documentation that clearly explains the semantics of modifications to non-object values obtained through subscripts. It appears that the language behaves as I would like it to, but I'm not comfortable relying on this behavior while it seems inconsistent with the documentation.
Array is implemented using copy-on-write, so it is not in fact copied each time it is assigned but only when it needs to be as determined by its internal state. It seems this behaviour is implemented in such a way that it is not triggered after being returned from a subscript.
update
Array subscripts are implemented using addressors, essentially the subscript accesses the array element directly. You can read some details in this document: https://github.com/apple/swift/blob/master/docs/proposals/Accessors.rst
Particularly note the section Mixed addressors, quote: 'Mixed addressors have now been adopted by Array to great success', perhaps dictionaries are using the same system now.
Also see this tweet: https://mobile.twitter.com/slava_pestov/status/778488750514970624
by someone who apparently works on the swift compiler at Apple, the related thread has some interesting links.
But essentially the answer to your question is that this isn't documented in a user friendly way, it is using special optimisations behind the scenes to make sure it works efficiently. I agree that a detailed explanation in the documentation would be helpful!
If you are concerned at using undocumented behaviour in your code a workaround would be to wrap your value type in a class before storing it in an array or dictionary. But it seems unlikely that the Swift team will make a change that breaks existing code in this way.

Difference between various type of Variable declaration in swift

I am quite a confused when and how to declare variables in particular points in Swift and its causing a headache for a new guy like me in SWIFT.
What is the difference between the following type of declarations? I have given my thoughts and understanding on them. Please rectify me with your solution if I am wrong and be a bit explanatory so that I can know the actual and exact answer.
Array -
1) var arr = NSArray()//I think its an instance of immutable NSArray type
2) var arr = NSMutableArray()
3) var arr = Array()//I have no idea of difference between NSArray and Array type. Might be both are same
4) var arr : NSMutableArray?//Creates an optional type but how is it different from line no.2
5) var arr : NSMutableArray = []//creates an empty array NSMutableArray type and again how is it different from line no.2 & 3
Please clarify a bit clearly so that my confusion level would be a bit clear. Thanks
Array is a swift type where as NSArray is an objective C type. NS classes support dynamic-dispatch and technically are slightly slower to access than pure swift classes.
1) var arr = NSArray()
arr is an NSArray() here - you can re-assign things to arr but you can't change the contents of the NSArray() - this is a bad choice to use IMO because you've put an unusable array into the variable. I really can't think of a reason you would want to make this call.
2) var arr = NSMutableArray()
Here you have something usable. because the array is mutable you can add and remove items from it
3) var arr = Array()
This won't compile - but var arr = Array<Int>() will.
Array takes a generic element type ( as seen below)
public struct Array<Element> : CollectionType, MutableCollectionType, _DestructorSafeContainer {
/// Always zero, which is the index of the first element when non-empty.
public var startIndex: Int { get }
/// A "past-the-end" element index; the successor of the last valid
/// subscript argument.
public var endIndex: Int { get }
public subscript (index: Int) -> Element
public subscript (subRange: Range<Int>) -> ArraySlice<Element>
}
4) var arr : NSMutableArray?
You are defining an optional array here. This means that arr starts out with a value of nil and you an assign an array to it if you want later - or just keep it as nil. The advantage here is that in your class/struct you won't actually have to set a value for arr in your initializer
5) var arr : NSMutableArray = []
It sounds like you are hung up on confusion about Optional values.
Optional means it could be nil or it could not
When you type something as type? that means it is nil unless you assign it something, and as such you have to unwrap it to access the values and work with it.
#G.Abhisek at first about you question. var arr: NSMutableArray = [] and var arr = NSMutableArray() means the same. the first one means, i ask the compiler to create a variable of type NSMutableArray and initialize it as an empty NSMutableArray. the second one means, i ask the compiler to create a variable and assign to it an empty initialized NSMutableArray. in the second case the compiler has to infer the right type of the variable, in the first case i did it by myself. still, the result will be the same. var arr1: Array<AnyObject> = [] and var arr2: NSMutableArray = [] are totally different things!. arr1 srores value type Array, arr2 stores reference to the instance of an empty NSMutableArray class. you can write let arr2: NSMutableArray = [] and next you can add an object there ... but you are not able to do thinks like arr2 = ["a","b"]. arr2 is constant, not variable, so the value stored there is imutable.
i am again close to my computer ... in the code below, you can see the main differences between swift and foundation arrays
import Foundation
let arr1: NSMutableArray = []
arr1.addObject("a")
arr1.addObject(10)
arr1.forEach {
print($0, $0.dynamicType)
/*
a _NSContiguousString
10 __NSCFNumber
*/
}
var arr2: Array<Any> = []
arr2.append("a")
arr2.append(10)
arr2.forEach {
print($0, $0.dynamicType)
/*
a String
10 Int
*/
}
var arr3: Array<AnyObject> = []
arr3.append("a")
arr3.append(10)
arr3.forEach {
print($0, $0.dynamicType)
/*
a _NSContiguousString
10 __NSCFNumber
*/
}
print(arr1.dynamicType, arr2.dynamicType, arr3.dynamicType)
// __NSArrayM Array<protocol<>> Array<AnyObject>

How do you use the map function in Swift?

I'm trying to understand how .map works and all of my searches are returning examples that aren't helping me resolve my issue. From my understanding .map is a cleaner way of performing a for-in loop, the only difference is that .map replaces your original creates a new array and for-in just alters your original arrays values.
Attempt
In the code example below, I'm expecting the .map function to replace my wheels array with new Tire objects whose state properties are all set to .Flat.
This is a playground-ready version of what I'm trying to accomplish in my program:
enum State {
case Ok, Flat
}
class Tire {
var state = State.Ok
init(t: State) {
state = t
}
}
var wheels = [Tire(t: .Ok), Tire(t: .Ok), Tire(t: .Ok)]
wheels = wheels.map { $0.state = .Flat }
Result
error: cannot convert value of type '()' to closure result type 'Tire'
wheels = wheels.map { $0.state = .Flat }
~~~~~~~~~^~~~~~~
Question
In the given situation, how can I set all of my Tire objects states to .Flat using .map?
There are 2 similar key functions which perform similar operations, the basic purpose of which is to take an array and build another array from it:
func map(transform:(R)->T) -> [T] --- Map takes an array of elements of one type and converts it to an array of elements of (potentially) another type, by calling a transform function on each element in turn. So you can convert an array of Int's to an array of strings:
[1, 2, 3, 4].map { "\($0)" } // --> ["1", "2", "3", "4"]
func filter(predicate:(T)->Boolean) -> [T] -- Filter takes an array of elements and converts it to an array of elements of the same type, but only includes those elements for which predicate returns true. So you can filter an array of ints to leave only the even numbers:
[1, 2, 3, 4].filter { $0 % 2 == 0 } // --> [ 2, 4]
There are other variants, such as flatMap which takes [[T]] and turns it into [T] by iterating over the input and array and appending the contents of each array to an output array:
[ [1, 2], [3, 4]].flatMap() // --> [1, 2, 3, 4]
It's also worth nothing that the concept behind map is that, in simplistic terms, it can be used to map any input type to an output type, so you can define:
func <R, T> map(in:R?, transform:(R)->T) -> T?
for example, which would translate any optional input type into an optional output type given a function that translates the base type.
The problem is $0.state = .Flat is an assignment. It does not return a value. Try this:
wheels = wheels.map { w in
w.state = .Flat
return w
}
map does not replace anything. It projects each element from your array to a new array by applying the transformation block. You can choose to assign this new array to the old array, but otherwise it will not alter the original array.

Optional vs Bound value assigning var from array

I want to check if there is a value in a array and if so assign to a String using a if-left statement:
if let scoreValue = scoreValueArray[element!]{
// do something with scoreValue
}
Error: Bound value in a conditional binding must be of optional type
So tried changing the ! to ? but error persists.
Any input appreciated.
scoreValueArray is an array of strings, where a String value is appended to array if a condition is met, then array is saved to NSUserdefaults.
So element is a int which corresponds to a index in the array, bt only if the index is occupied with a String, so
scoreValueArray[element!]
could return an 'Index out of bounds', hence want to use the if-let.
Although the accepted answer clearly puts why optional binding is not available in the current implementation, it doesn't provide with a solution.
As it is shown in this answer, protocols provide an elegant way of safely checking the bounds of an array. Here's the Swift 2.0 version:
extension Array {
subscript (safe index: Int) -> Element? {
return indices ~= index ? self[index] : nil
}
}
Which you can use like this:
let fruits = ["Apple", "Banana", "Cherry"]
if let fruit = fruits[safe: 4] {
// Do something with the fruit
}
It's not clear what type your scoreValueArray is, but for the sake of this answer, I'm going to assume it's an array of Int.
var scoreValueArray: Array<Int>
Now, if we look the definition of the Array struct, we'll find this:
struct Array<T> : MutableCollectionType, Sliceable {
// other stuff...
subscript (index: Int) -> T
// more stuff
}
So, calling the subscript method on our array (which is what we do when we say scoreValueArray) returns a non-optional. And non-optionals cannot be used in the conditional binding if let/if var statements.
We can duplicate this error message in a more simple example:
let foo: Int = 3
if let bar = foo {
// same error
}
This produces the same error. If we instead do something more like the following, we can avoid the error:
let foo: Int? = 3
if let bar = foo {
// perfectly valid
}
This is different from a dictionary, whose subscript method does return an optional (T?). A dictionary will return a value if the key passed in the subscript is found or nil if there is no value for the passed key.
We must avoid array-index-out-of-bounds exceptions in the same way we always do... by checking the array's length:
if element < scoreValueArray.count {
scoreValue = scoreValueArray[element]
}