2017-10-20 9 views
-1

나는 오류를 해결하는 데 도움이 필요 :오류를 해결하는 방법 :`...`형식의 인수 목록을 사용하여`...`형식의 이니셜 라이저를 호출 할 수 없습니까?

Cannot invoke initializer for type 'QuotesViewController.RandomItems' with an argument list of type '(items: [String], seen: Int)'

이 내 코드입니다 :

let a = QuotesViewController.RandomItems(items: ["hello"], seen: 2) //<-- Error 

존재하지 않는 initialiser를 호출

struct RandomItems: Codable 
{ 
    var items : [String] 
    var seen = 0 

    init(_ items:[String]) 
    { self.items = items } 

    mutating func next() -> String 
    { 
     let index = Int(arc4random_uniform(UInt32(items.count - seen))) 
     let item = items.remove(at:index) 
     items.append(item) 
     seen = (seen + 1) % items.count 
     return item 
    } 
    func toPropertyList() -> [String: Any] { 
     return [ 
      "items": items, 
      "seen": seen 
     ] 
    } 


    } 
} 

extension QuotesViewController.RandomItems { 
    init?(propertyList: [String: Any]) { 
     return nil 
    } 
} 

let a = QuotesViewController.RandomItems(items: ["hello"], seen: 2) //<-- Error 
let data: Data = try! JSONEncoder().encode(a) 
let b = try! JSONDecoder().decode(QuotesViewController.RandomItems.self, from: data) 
+1

글쎄'QuotesViewController.RandomItems'는'init이없는이 '(항목 : 본) – Hamish

답변

1

이 줄. 당신은 단지 하나를 할 필요가, 당신은 initialisers에 여분의 물건을 추가해야하는 경우, 그래서

init(_ items: [String]) 
{ 
    self.init(items: items, seen: 0) 
} 

에 기존 initialiser을 변경, 좋은 측정을 위해

init(items:[String], seen: Int) 
{ 
    self.items = items 
    self.seen = seen 
} 

이 같은 하나를 만들기 장소.

또는 하나의 initialiser이

init(items:[String], seen: Int = 0) 
{ 
    self.items = items 
    self.seen = seen 
}