Swift Any Array not accessing Struct Methods - arrays

So, I have the following code in Swift 2:
struct IntToken {
var value:Int
init(val:Int) {
self.value = val
}
mutating func add(val:IntToken) {
self.value += val.value
}
}
var table = [Any]()
table.append(IntToken(val:3))
table.append(IntToken(val:4))
table[0].add(table[1])
This gives me the following error
Playground execution failed: /var/folders/jx/bhltcyc90117d2wx_r82p4fr0000gn/T/./lldb/73237/playground71.swift:22:6: error: value of type 'Any' (aka 'protocol<>') has no member 'add'
table[0].add(table[1])
~~~~~^~~ ~~~
The issue is, I am trying to create an Array, that will contain different type of objects, not just IntToken's, but I also want to be able to access the elements of that array and use their methods on one another. Whenever I try to use the Any array, however, it doesn't allow me to do this, because it's reading the accessed struct instance as an any type.
What's a good way to accomplish what I am trying to do?

Starting with your original struct:
struct IntToken {
var value:Int
init(val:Int) {
self.value = val
}
mutating func add(val:IntToken) {
self.value += val.value
}
}
Do like this:
var table = [Any]()
table.append(IntToken(val:3))
table.append(IntToken(val:4))
var it = table[0] as! IntToken // take it out with cast and var ref
it.add(table[1] as! IntToken) // add with cast; `it` is now IntToken(val:7)
table[0] = it // put it back in (if you want to)

i slightly modified matt's answer (accepted answer) to show how to avoid crash in case some table element has other type as IntToken.
var table:[Any] = []
table.append(IntToken(val:3))
table.append(IntToken(val:4))
if let it0 = table[0] as? IntToken,
let it1 = table[1] as? IntToken {
var it0 = it0
it0.add(it1)
table[0] = it0
}
print(table) // [IntToken(value: 7), IntToken(value: 4)]
I prefer to modify your IntToken
struct IntToken {
var value:Int
func add1(token: IntToken)->IntToken {
var token = token
token.value += value
return token
}
}
and remove any 'mutating' function from it. Now the original code snippet could be modified to 'more functional' and easy to understand version
var table = [Any]()
table.append(IntToken(value:3))
table.append(IntToken(value:4))
if let it1 = table[1] as? IntToken,
let v = (table[0] as? IntToken)?.add1(it1) {
table[0] = v
}
print(table) // [IntToken(value: 7), IntToken(value: 4)]

Related

How to use two-dimensions array in Swift?

So I have this array var arrayItinerario: Array<Any> = [] which is intended to hold arrays of type Itinerario, var temporalArray: Array<Itinerario> = []
Next, this arrayItinerario would later be used to access properties from the struct Itinerario from where the array temporalArray type comes from.
cell.siteLabel.text = "\([arrayItinerario[indexPath.section]][indexPath.row].ubicacion)"
The problem is that arrayItinerario is not an Itinerario type object which make it impossible to access ubicacion to make an example
I have tried
let object = [arrayItinerario[indexPath.section]][indexPath.row] as! Itinerario
But the cast throws an error. How can I do to access properties from the arrays temporalArraythat are inside arrayItinerario?
Note: I am using indexPath because I am filling table cells
var arrayItinerario: [[Itinerario]] = []
//fill data
var temporalArray: [Itinerario] = []
arrayItinerario.append(temporalArray)
cell.siteLabel.text = "\(arrayItinerario[indexPath.section][indexPath.row].ubicacion)"
or
var arrayItinerario: Array<Any> = []
var temporalArray: Array<Itinerario> = []
guard let temp = arrayItinerario[indexPath.section] as? Array<Itinerario>{
return
}
cell.siteLabel.text = "\(temp[indexPath.row].ubicacion)"
Here's an implementation I've used in a few projects:
import Foundation
class Array2D<T> {
var cols:Int, rows:Int
var matrix:[T?]
init(cols: Int, rows: Int, defaultValue:T?) {
self.cols = cols
self.rows = rows
matrix = Array(repeating: defaultValue, count: cols*rows)
}
subscript(col:Int, row:Int) -> T? {
get{
return matrix[cols * row + col]
}
set{
matrix[cols * row + col] = newValue
}
}
func colCount() -> Int { self.cols }
func rowCount() -> Int { self.rows }
}
Because it's generic you can store whatever type you like in it. Example for Ints:
// Create 2D array of Ints, all set to nil initially
let arr = Array2D<Int>(cols: 10, rows: 10, defaultValue: nil)

Get struct properties from string - swift

I declared a struct with 4 properties ( informationA, informationB, informationC, informationD ).
Also I've declared an array like this (The array includes some names of the my_struct properties as "strings" :
let keys = ["informationA", "informationB", "informationC"]
Now I'd like a for-loop to go through the "keys"-array and print out the struct property values for the current string ("informationA", "informationB", "informationC").
struct my_struct {
var informationA = "test"
var informationB = "test...test"
var informationC = "test...test"
var informationD = "test...test..."
}
func getInformation() {
let keys = ["informationA", "informationB", "informationC"]
for i in keys {
print(my_struct.i) // ERROR: Type 'my_struct' has no member 'i'
// should print ---> "test", "test...test", "test...test"
}
}
Using the code from above I'm getting this error ERROR: Type 'my_struct' has no member 'i'.
Is there a way to avoid this message and achieve the result I'd like to get?
What you are looking for is reflection:
struct MyStruct {
var informationA = "test"
var informationB = "test...test"
var informationC = "test...test"
var informationD = "test...test..."
}
func getInformation() {
let my_struct = MyStruct()
let keys = ["informationA", "informationB", "informationC"]
let m = Mirror(reflecting: my_struct)
let properties = Array(m.children)
for k in keys {
if let prop = properties.first(where: { $0.label == k }) {
print(prop.value)
}
}
}

Swift 2.0 - ERROR: Immutable value of type '[String]' only has mutating members named 'append'

I am trying to write a method which extracts a HTML tag into a array because I want to parse a web page in a tree structure.
func extractStringFromHTMLInsideTags(htmlString:String, htmlTagPairArray:[String], saveToArray:[String]) -> String
{
var htmlNSString = htmlString as NSString
var lenght = htmlNSString.length
var openingTag = htmlTagPairArray[0] as NSString
var openingTagLength = openingTag.length
var closingTag = htmlTagPairArray[1] as NSString
var closingTagLength = closingTag.length
if (htmlString.rangeOfString(htmlTagPairArray[0]) != nil)
{
let rangeStart:NSRange! = htmlNSString.rangeOfString(htmlTagPairArray[0], options: NSStringCompareOptions.CaseInsensitiveSearch)
var rangeEnd:NSRange! = htmlNSString.rangeOfString(htmlTagPairArray[1], options: NSStringCompareOptions.CaseInsensitiveSearch)
let startTagIndex: Int = rangeStart.location + openingTagLength
let boldTextLenght: Int = rangeEnd.location - rangeStart.location - openingTagLength
let endTagIndex: Int = startTagIndex + boldTextLenght
let startIndex = advance(htmlString.startIndex,startTagIndex)//advance as much as you like
let endIndex = advance(htmlString.startIndex,endTagIndex)
let range = startIndex..<endIndex
var resultString = htmlString.substringWithRange( range )
saveToArray.append(resultString)
resultString = htmlString.stringByReplacingOccurrencesOfString(htmlTagPairArray[0] + resultString + htmlTagPairArray[1], withString: resultString, options: nil, range: nil)
if (resultString.rangeOfString(htmlTagPairArray[0]) != nil)
{
resultString = extractStringFromHTMLInsideTags(resultString,htmlTagPairArray:htmlTagPairArray, saveToArray:saveToArray)
}
return resultString
}
return htmlString
}
On the line:
saveToArray.append(resultString)
I am getting the error:
Immutable value of type '[String]' only has mutating members named
'append'
The error states that saveToArray is immutable. I thought that the array is copied by reference...?
Why is this happening?
( I am using Swift 2.0 and Xcode 7.1 ).
Parameters passed in methods are immutable (let) by default.
Add the keyword var to make them mutable
func extractStringFromHTMLInsideTags(htmlString:String, htmlTagPairArray:[String], var saveToArray:[String]) -> String
{ ...

Changing The value of struct in an array

I want to store structs inside an array, access and change the values of the struct in a for loop.
struct testing {
var value:Int
}
var test1 = testing(value: 6 )
test1.value = 2
// this works with no issue
var test2 = testing(value: 12 )
var testings = [ test1, test2 ]
for test in testings{
test.value = 3
// here I get the error:"Can not assign to 'value' in 'test'"
}
If I change the struct to class it works. Can anyone tell me how I can change the value of the struct.
Besides what said by #MikeS, remember that structs are value types. So in the for loop:
for test in testings {
a copy of an array element is assigned to the test variable. Any change you make on it is restricted to the test variable, without doing any actual change to the array elements. It works for classes because they are reference types, hence the reference and not the value is copied to the test variable.
The proper way to do that is by using a for by index:
for index in 0..<testings.count {
testings[index].value = 15
}
in this case you are accessing (and modifying) the actual struct element and not a copy of it.
Well I am going to update my answer for swift 3 compatibility.
When you are programming many you need to change some values of objects that are inside a collection. In this example we have an array of struct and given a condition we need to change the value of a specific object. This is a very common thing in any development day.
Instead of using an index to determine which object has to be modified I prefer to use an if condition, which IMHO is more common.
import Foundation
struct MyStruct: CustomDebugStringConvertible {
var myValue:Int
var debugDescription: String {
return "struct is \(myValue)"
}
}
let struct1 = MyStruct(myValue: 1)
let struct2 = MyStruct(myValue: 2)
let structArray = [struct1, struct2]
let newStructArray = structArray.map({ (myStruct) -> MyStruct in
// You can check anything like:
if myStruct.myValue == 1 {
var modified = myStruct
modified.myValue = 400
return modified
} else {
return myStruct
}
})
debugPrint(newStructArray)
Notice all the lets, this way of development is safer.
The classes are reference types, it's not needed to make a copy in order to change a value, like it happens with structs. Using the same example with classes:
class MyClass: CustomDebugStringConvertible {
var myValue:Int
init(myValue: Int){
self.myValue = myValue
}
var debugDescription: String {
return "class is \(myValue)"
}
}
let class1 = MyClass(myValue: 1)
let class2 = MyClass(myValue: 2)
let classArray = [class1, class2]
let newClassArray = classArray.map({ (myClass) -> MyClass in
// You can check anything like:
if myClass.myValue == 1 {
myClass.myValue = 400
}
return myClass
})
debugPrint(newClassArray)
To simplify working with value types in arrays you could use following extension (Swift 3):
extension Array {
mutating func modifyForEach(_ body: (_ index: Index, _ element: inout Element) -> ()) {
for index in indices {
modifyElement(atIndex: index) { body(index, &$0) }
}
}
mutating func modifyElement(atIndex index: Index, _ modifyElement: (_ element: inout Element) -> ()) {
var element = self[index]
modifyElement(&element)
self[index] = element
}
}
Example usage:
testings.modifyElement(atIndex: 0) { $0.value = 99 }
testings.modifyForEach { $1.value *= 2 }
testings.modifyForEach { $1.value = $0 }
How to change Array of Structs
for every element:
itemsArray.indices.forEach { itemsArray[$0].someValue = newValue }
for specific element:
itemsArray.indices.filter { itemsArray[$0].propertyToCompare == true }
.forEach { itemsArray[$0].someValue = newValue }
You have enough of good answers. I'll just tackle the question from a more generic angle.
As another example to better understand value types and what it means they get copied:
struct Item {
var value:Int
}
func change (item: Item, with value: Int){
item.value = value // cannot assign to property: 'item' is a 'let' constant
}
That is because item is copied, when it comes in, it is immutable — as a convenience.
Had you made Item a class type then you were able to change its value.
var item2 = item1 // mutable COPY created
item2.value = 10
print(item2.value) // 10
print(item1.value) // 5
This is very tricky answer. I think, You should not do like this:
struct testing {
var value:Int
}
var test1 = testing(value: 6)
var test2 = testing(value: 12)
var ary = [UnsafeMutablePointer<testing>].convertFromArrayLiteral(&test1, &test2)
for p in ary {
p.memory.value = 3
}
if test1.value == test2.value {
println("value: \(test1.value)")
}
For Xcode 6.1, array initialization will be
var ary = [UnsafeMutablePointer<testing>](arrayLiteral: &test1, &test2)
It is possible to use the map function to get this effect - essentially creating a new array
itemsArray = itemsArray.map {
var card = $0
card.isDefault = aCard.token == token
return card
}
I ended up recreating a new array of struct see the example below.
func updateDefaultCreditCard(token: String) {
var updatedArray: [CreditCard] = []
for aCard in self.creditcards {
var card = aCard
card.isDefault = aCard.token == token
updatedArray.append(card)
}
self.creditcards = updatedArray
}
I tried Antonio's answer which seemed quite logical but to my surprise it does not work. Exploring this further I tried the following:
struct testing {
var value:Int
}
var test1 = testing(value: 6 )
var test2 = testing(value: 12 )
var testings = [ test1, test2 ]
var test1b = testings[0]
test1b.value = 13
// I would assume this is same as test1, but it is not test1.value is still 6
// even trying
testings[0].value = 23
// still the value of test1 did not change.
// so I think the only way is to change the whole of test1
test1 = test1b

Swift 3 - Function for Wrapping an Array

As I try to learn Swift 3, I am attempting to "Wrap an Array of Elements". In Swift 3 Playgrounds, I was able to implement code that wraps an array. My problem occurs when I try to create a function that implements my code.
If you take the following code and copy-paste it to a Swift 3 Playground then you will likely see what I am trying to do. Change the selectedElement and on the right you will see the correct newArray. You can interchange the different elements for the selectedElement and the newArray will change accordingly.
I noted one of my failed attempts at turning this into a function.
import UIKit
let myArray = ["a", "b", "c", "d", "e"]
let selectedElement = "a"
//func arrayWrapper(inputArray: Array<String>) -> Array<String> {
var oldArray = [String]()
var priorElements = [String]()
var newArray = [String]()
for element in myArray {
if element == selectedElement || oldArray.count > 0 {
oldArray.append(element)
} else {
priorElements.append(element)
}
newArray = oldArray + priorElements
}
//return newArray
//}
priorElements
oldArray
oldArray + priorElements
newArray
Your method works fine.
The only problem I see is that you are trying to access the variables created inside the function outside of the function scope.
//priorElements
//oldArray
//
//oldArray + priorElements
arrayWrapper(inputArray: myArray)
Well, your non-function solution to this problem takes two inputs - the array you want to wrap, and the element you want it to wrap at. Therefore, your function should have two parameters as well:
// note the second parameter
func arrayWrapper(inputArray: Array<String>, selectedElemented: String) -> Array<String> {
var oldArray = [String]()
var priorElements = [String]()
var newArray = [String]()
for element in myArray {
if element == selectedElement || oldArray.count > 0 {
oldArray.append(element)
} else {
priorElements.append(element)
}
newArray = oldArray + priorElements
}
return newArray
}
Here is a more general version of this function, as an extension of Array:
extension Array where Element : Equatable {
func wrap(around selectedElement: Element) -> Array<Element> {
var oldArray = [Element]()
var priorElements = [Element]()
var newArray = [Element]()
for element in self {
if element == selectedElement || oldArray.count > 0 {
oldArray.append(element)
} else {
priorElements.append(element)
}
newArray = oldArray + priorElements
}
return newArray
}
}
// usage
myArray.wrap(around: selectedElement)

Resources