如何调用方法按年过滤

时间:2016-07-10 09:12:44

标签: swift

我正在做一个简单的例子。 我正在尝试使用func:filterByYear按年过滤电影。 我在底部的一行中有错误: 'var filterYear = MovieArchive.filterByYear(1980)'编译器信息是:'类型'MovieArchive'没有成员filterByYear'

import UIKit

class Movie {
    let title: String
    let director: String
    let releaseYear: Int


    init(title: String, director: String, releaseYear: Int){
        self.title = title
        self.director = director
        self.releaseYear = releaseYear
    }
}

class MovieArchive{
    var movies : [Movie]
    init(movies:[Movie]){
        self.movies = movies

    func filterByYear(year:Int) -> [Movie]{
        var filteredArray = [Movie]()
        for movie in movies{
            if movie.releaseYear == year {
                filteredArray.append(movie)
            }
        }
        return filteredArray
    }
    }
}


var newMovie1 = Movie(title: "IT", director: "S.S", releaseYear: 1980)
var newMovie2 = Movie(title: "PP", director: "O.N", releaseYear: 2003)
var moviesArray = [newMovie1, newMovie2]

var myArchive = MovieArchive(movies: moviesArray)
var filterYear = MovieArchive.filterByYear(1980)
var firstMovie = filterYear[0]
print(firstMovie)

2 个答案:

答案 0 :(得分:1)

您正在调用类本身的方法,而不是它的实例。你必须像这样创建一个类的实例:

let myMovieArchive = MovieArchive(movies: [一些数组])

然后在实例上调用该方法。

print(myMovieArchive.filterByYear)

因此,在您的情况下,请在myArchive上调用,而不是MovieArchive

答案 1 :(得分:-1)

即使问题已经得到解答,您也可以简化filterByYear方法,使其更加 Swifty

func filterByYear(year:Int) -> [Movie]
{
    return movies.filter({ $0.releaseYear == year })
}