import UIKit
import SwiftUI
var str = "Hello, playground"
struct FianceItem: Identifiable,Codable {
public var id: UUID = UUID()
public var name: String
public var childs:[FianceItem] = []
}
var root=FianceItem(name: "root")
var childA=FianceItem(name: "childA")
root.childs.append(childA)
var childB=FianceItem(name: "childB")
childA.childs.append(childB)
print(root)
struct is a value type. When you assign it to another variable, its value is copied.
So order matters in this case.
This line is creating a copy of childA and putting it into the array of root.
root.childs.append(childA)
When you edit the original, the copy does not have childB.
Either reorder the code like Raja Kishan's answer or use class instead of struct.
Change your sequence
let contentView = DeveloperView()
var root=FianceItem(name: "root")
var childA=FianceItem(name: "childA")
var childB=FianceItem(name: "childB")
childA.childs.append(childB)
root.childs.append(childA)
print(root)
Related
What I want my swift code to do is take the two arrays initilized in view controller and then move them into the struct added. I want to do the transfer in view did load. I dont know what I am doing so I put some code that I thought might be helpful but right now my code is not compiling in view did load.
import UIKit
class ViewController: UIViewController {
var emptyA = [Int]()
var emptyb = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
added.init(emptyA, emptyb)
}
}
struct added {
var arrayOne = //emptyA
var arrayTwo = //emptyb
}
You need to declare your struct like this:
struct Added {
var arrayOne: [Int]
var arrayTwo: [UIImage]
}
Then to declare an instance you would do this:
let a = Added(arrayOne: emptyA, arrayTwo: emptyb)
Also, it's typically good form to start the name of your structs with a capital letter.
I have following struct:
struct PalletScan: Codable {
var deliveryId: String?
var userId: String?
var timestamp: String?
var tempPalletNr: String?
var tempLocation: String?
var tempPalletType: String?
var pallets: [MovementScan]?
//coding keys requried for translation API -> struct -> CoreData and CoreData -> struct -> API
enum CodingKeys: String, CodingKey {
case deliveryId = "TOID"
case userId = "UserId"
case timestamp = "TimeStamp"
}
mutating func appendMovementScan() {
var movementScan = MovementScan()
movementScan.locationId = self.tempLocation
movementScan.palletId = self.tempPalletNr
movementScan.palletType = self.tempPalletType
movementScan.timestamp = String(Date().timeIntervalSince1970)
print(movementScan)
self.pallets?.append(movementScan)
}
}
however self.pallets?.append(movementScan) does not adding anything to the pallets array. What am I missing? It must be trivial but can not find mistake.
Just change var pallets: [MovementScan]?
to
var pallets: [MovementScan] = [MovementScan]()
as #Carcigenicate you call append on nil value
var pallet is not initialized and it is an optional so when you append movementscan using ? , it wont be executed.
To fix this you have to some how initialize pallets array before appending to it .
One way can be simply initialize with empty array :
var pallets = [MovementScan]()
I'm trying to delete values of a lot of variables inside an array:
var fbUserID = String()
var fbUserName = String()
var meNickname = String()
var userIDOneSignal = String()
var deleteStrings = [fbUserID, fbUserName, meNickname, userIDOneSignal]
Is it possible to do something in line of this:
for i in deleteStrings {
i.removeAll()//remove all as in remove the values of each variable
}
I've also tried using deleteStrings[i].removeAll()
Due to value semantics you cannot mutate variables (as a pointer) from an array.
Rather than an array use a struct
struct User {
var fbUserID = "12"
var fbUserName = "Foo"
var meNickname = "Baz"
var userIDOneSignal = "123"
mutating func clear()
{
fbUserID = ""
fbUserName = ""
meNickname = ""
userIDOneSignal = ""
}
}
var user = User()
print(user.fbUserID) // "12"
user.clear()
user.fbUserID = ""
print(user.fbUserID) // ""
Simply delete the array elements
deleteStrings.removeAll()
If your class inherits from NSObject, you can use key value coding to access the fields by name:
class User: NSObject {
var fbUserID = String()
var fbUserName = String()
var meNickname = String()
var userIDOneSignal = String()
var deleteStrings = ["fbUserID", "fbUserName", "meNickname", "userIDOneSignal"]
func clearAll() {
deleteStrings.forEach { setValue("", forKey: $0) }
}
}
let user = User()
user.fbUserID = "12345"
user.fbUserName = "Joseph Doe"
user.meNickname = "Joe"
print(user.meNickname) // "Joe"
user.clearAll()
print(user.meNickname) // ""
If you want to delete/remove variable value then use optional otherwise your variable value only gets removed or become non-existence when it goes out of scope.
For Example:
var a: Int? = 5 // it have default value 5
a = nil // Now a have nil which is kind of telling that it contains nothing which is what you want to achieve
Now coming to your question.
Is it possible to do something in line of this:
for i in deleteStrings {
i.removeAll()
}
You are iterating over an array of strings and then for each string, you are trying to remove all the characters. First of all you will get error
error: cannot use mutating member on immutable value: 'i' is a 'let' constant
Even though you will correct is using var it will not achieve what you are trying to do i.e. I want to delete the variables value because still your fbUserID ... all other variables will have copies of the data you initialised with.
Now how to do it?
You can use optional to achieve it.
var fbUserID: String? = String()
var fbUserName: String? = String()
var meNickname: String? = String()
var userIDOneSignal: String? = String()
// To delete you will need to assign them nil
fbUserId = nil
Again, you can't do them over loop because var are of values type and when you add it to the list their copies get added.
I'm new to Realm and have been through the documentation a few times. I need to persist a [[String]] and have not found a way to do it yet
var tableViewArray = [[String]]()
I see the documentation pointing to Lists but I've been unsuccessful at implementing them. I'm showing my whole process here but just need help persisting my var tableViewArray = [[String]]()in Realm
This is my class
class TableViewArrays {
var tableViewArray = [[String]]() // populates the Main Tableview
/// add picker selection to tableview array
func appendTableViewArray(title: String, detail: String, icon: String ) {
var newRow = [String]()
newRow.append(title)
newRow.append(detail)
newRow.append(icon)
tableViewArray.append(newRow)
}
In the View Controller I instantiate the object
var tableViewArrays = TableViewArrays()
Then call the class function to populate the object
var tableViewArrays.appendTableViewArray(title: String, detail: String, icon: String )
Thank you for taking a look
I would make two Realm objects to be persisted, then nest them. Here's an example:
class RealmString: Object {
dynamic var value = ""
}
class RealmStringArray: Object {
let strings = List<RealmString>()
}
class TableViewArray{
let stringArrays = List<RealmStringArray>()
}
I can't say much about the efficiency of this method, but I suppose it should work for your purpose. Also, if you have a large amount of data, it may become a pain to persist each individual string, then string collection, the string collection collection.
create the classes
class TableViewRow: Object {
dynamic var icon = ""
dynamic var title = ""
dynamic var detail = ""
override var description: String {
return "TableViewRow {\(icon), \(title), \(detail)}" }
}
class EventTableView: Object {
let rows = List<TableViewRow>()
}
then instantiate the objects and append
let defaultTableview = EventTableView()
let rowOne = TableViewRow()
rowOne.icon = "man icon" ; rowOne.title = "War Hans D.O.P." ; rowOne.detail = "Camera Order Nike 2/11/17"
defaultTableview.rows.append(objectsIn: [rowOne])
How can I auto add a new class instance to an array?
Example:
class Product {
var name: String?
}
var products = [Product]()
How can I add a new instance of a Product class to the products Array? How can I append to the array?
I tried some code but I don't know how to reference the class in own class.
I tried something like this:
class Product {
var name: String?
init() {
products.append(Produt)
}
var products = [Product]()
Thanks!
If you want your newly created object stored in products array then you need to declare it as static property so that it is shared by all instance otherwise it will just add first object for your every instance.
class Product {
var name: String?
static var products = [Product]()
init() {
Product.products.append(self)
}
init(name: String) {
self.name = name
Product.products.append(self)
}
}
Now use this products array using Product.products.
_ = Product(name: "One")
_ = Product(name: "two")
print(Product.products)
I dont't know why you need it, but you can use
class Product {
static var products: [Product] = []
var name: String?
init() {
products.append(self)
}
}
Have you tried products.append(self) ?