mike vorisis mike vorisis - 5 months ago 15
iOS Question

How can i add a value in an Array which is inside a struct (Swift)

I have this Struct:

struct Event {
var nameEvent: String
var nameMagazi: String
var objectId: String
var typeEvent: NSArray
}


and I use it to make a Dictionary with these four variables like this:

for object in objects {

let post = object["idEvent"] as? PFObject
let post2 = post!["idMagazi"] as? PFObject
let post3 = object["eventType"] as? PFObject
let nameevent = post!["name"] as! String
let idevent = post?.objectId
let namemagazi = post2!["name"] as! String
let typeevent = post3!["EventName"] as! String
var count = 0
for index in 0...self.i {
if self.events[index]?.objectId == idevent {
count += 1
self.dump = index
}

}


if count == 0 {

self.events[self.countids] = Event(nameEvent: nameevent , nameMagazi: namemagazi , objectId: idevent!, typeEvent: [typeevent])
self.countids += 1
}else{

self.events[self.dump]!.typeEvent = [self.events[self.dump]!.typeEvent, typeevent]


}

self.i += 1
}


As you can see if i find a duplicate i want only to add the typeevent to the existing the Array.

self.events[self.dump]!.typeEvent = [self.events[self.dump]!.typeEvent, typeevent]


this line works but it's like it returns array inside another array like this:

(
(
(
(
(
(
"\U0395\U03bb\U03bb\U03b7\U03bd\U03b9\U03ba\U03ac"
),
mainstream
),
hiphop
),
house
),
rnb
),
Live
)

Answer

To add a value to the array typeEvent create a mutating function in the struct

struct Event {
  var nameEvent: String
  var nameMagazi: String
  var objectId: String
  var typeEvent: [String]

  mutating func addEvent(event : String) {
    typeEvent += [event]
  }
}

I changed typeEvent from type unspecified NSArray to the Swift native type [String]

Now you can write

var event = Event(nameEvent: "Foo", nameMagazi: "Bar", objectId: "Baz", typeEvent: ["alpha", "beta", "gamma"])
event.addEvent("delta")
event.typeEvent // -> ["alpha", "beta", "gamma", "delta"]