如何在结构内部的数组中添加值(Swift)

时间:2016-07-06 13:51:28

标签: ios arrays swift struct

我有这个结构:

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

我用它来制作一个包含这四个变量的字典:

     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
                        }

正如您所看到的,如果我发现重复,我只想将typeevent添加到现有数组中。

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

这一行有效,但就像它返回另一个数组中的数组一样:

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

1 个答案:

答案 0 :(得分:1)

要向数组typeEvent添加值,请在struct

中创建一个变异函数
struct Event {
  var nameEvent: String
  var nameMagazi: String
  var objectId: String
  var typeEvent: [String]

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

我将typeEvent从未指定的NSArray类型更改为Swift原生类型[String]

现在你可以写

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