为什么我必须在Swift中创建一个向数组添加项的函数?

时间:2018-03-08 03:34:03

标签: arrays swift

我正在编写一个教程,然后我创建了一个让我难过的拼写错误。我知道如何纠正代码,但我很想知道当我尝试向数组添加项目时,为什么这个代码不能编译,除非它在函数内完成?这段代码中的拼写错误是它需要在init函数中。因此我很好奇,为什么我不能在函数之外的数组中添加项?是因为向数组中添加项目是某种类型的操作,除非它在函数内部,否则不会发生此操作?

import Foundation

final class PersistencyManager {

  private var albums = [Album]()


  //dummy list of albums...
  let album1 = Album.init(title: "Best of Bowie", artist: "David Bowie", genre: "Pop", coverUrl: "https://s3.amazonaws.com/CoverProject/album/album_david_bowie_best_of_bowie.png", year: "1992")

  let album2 = Album.init(title: "It's My Life", artist: "No Doubt", genre: "Pop", coverUrl: "https://s3.amazonaws.com/CoverProject/album/album_no_doubt_its_my_life_bathwater.png", year: "2003")

  let album3 = Album.init(title: "Nothing Like The Sun", artist: "Sting", genre: "Pop", coverUrl: "https://s3.amazonaws.com/CoverProject/album/album_sting_nothing_like_the_sun.png", year: "1999")

  let album4 = Album.init(title: "American Pie", artist: "Madonna", genre: "Pop", coverUrl: "https://s3.amazonaws.com/CoverProject/album/album_u2_staring_at_the_sun.png", year: "2000")



  //the line of code shows a compile error that reads "expected declaration"
  albums = [album1, album2, album3, album4]

}

2 个答案:

答案 0 :(得分:2)

您不需要将项添加到数组的功能。但是你不能只将代码粘贴到你想要的地方。它需要位于适当的位置,例如函数或适当的代码块。类的顶级不是允许运行代码的地方。

以下对代码的重新编写可以正常工作:

final class PersistencyManager {
    private var albums = [
        Album.init(title: "Best of Bowie", artist: "David Bowie", genre: "Pop", coverUrl: "https://s3.amazonaws.com/CoverProject/album/album_david_bowie_best_of_bowie.png", year: "1992"),

        Album.init(title: "It's My Life", artist: "No Doubt", genre: "Pop", coverUrl: "https://s3.amazonaws.com/CoverProject/album/album_no_doubt_its_my_life_bathwater.png", year: "2003"),

        Album.init(title: "Nothing Like The Sun", artist: "Sting", genre: "Pop", coverUrl: "https://s3.amazonaws.com/CoverProject/album/album_sting_nothing_like_the_sun.png", year: "1999"),

        Album.init(title: "American Pie", artist: "Madonna", genre: "Pop", coverUrl: "https://s3.amazonaws.com/CoverProject/album/album_u2_staring_at_the_sun.png", year: "2000")
    ]
}

这里的不同之处在于它现在只是一个声明和初始化。

答案 1 :(得分:1)

因为您在UIViewController初始化之前访问了控制器实例。如果你把它放在函数中,你必须在另一个方法中调用这个方法,即(viewDidLoad)。所以那时你的viewcontroller被初始化,所以你可以使用实例。

如果您想要实现这些目标,可以使用lazy初始化。