在元组中附加值

时间:2016-05-10 09:28:13

标签: ios swift tuples

任何人都可以告诉我如何在tuple函数的favBt中添加值。 我尝试过两种不同的方法但同样的错误?

fatal error: unexpectedly found nil while unwrapping an Optional value

1. appendData.tupple.append(values)
2. appendData.tupple.append(url,image)

enter image description here

var objects : [(String, String)] = [
                ("https://www.youtube.com/watch?v=9h30Bx4Klxg","1.jpg"),
                ("https://www.youtube.com/watch?v=ij_0p_6qTss","2.jpg"),
                ("https://www.youtube.com/watch?v=AJtDXIazrMo","3.jpg"),
                ("https://www.youtube.com/watch?v=H202k7KfZL0","4.jpg"),
                ("https://www.youtube.com/watch?v=CGyEd0aKWZE","5.jpg"),
                ("https://www.youtube.com/watch?v=AtKZKl7Bgu0","6.jpg"),
                ("https://www.youtube.com/watch?v=4SYlLi5djz0","7.jpg")]

    func favBt(sender: UIButton){

            var btn : NSInteger
            btn = sender.tag as NSInteger

            let (url,image) = objects[btn]

            let values = (url, image)
            print(values)

            let appendData = ViewController()

            appendData.tupple.append(values)

            print(appendData.tupple[btn])

          }

    In my ViewController Class

    class ViewController: UIViewController{
       var tuple : [(String, String)]?
    }

2 个答案:

答案 0 :(得分:0)

let appendData = ViewController()我从功能中创建了这个方面。

将其替换为var tuple : [(String, String)]?

var tuple : [(String, String)] = []

答案 1 :(得分:0)

您没有初始化“元组”变量。您可以尝试以下代码:

class ViewController: UIViewController{
   var tuple : [(String, String)]?

   override func viewDidLoad() {
      super.viewDidLoad()
      self.tuple = [(String, String)]()
   }
}