2017-02-24 31 views
1
方法重載

我試圖做的方法斯威夫特重載用下面的代碼:「不正確的參數標籤」當斯威夫特

struct Game { 
    private let players: [UserProfile] //set in init() 
    private var scores: [Int] = [] 

    mutating func setScore(_ score: Int, playerIndex: Int) { 

     //... stuff happening ... 

     self.scores[playerIndex] = score 
    } 

    func setScore(_ score: Int, player: UserProfile) { 
     guard let playerIndex = self.players.index(of: player) else { 
      return 
     } 

     self.setScore(score, playerIndex: playerIndex) 
    } 
} 

我上self.setScore線得到一個錯誤:

Incorrect argument labels in call (have _:playerIndex:, expected _:player:)

我一直在看這段代碼一段時間,但不知道爲什麼這不起作用。任何提示?

+0

你試圖調用非'mutating'方法裏面'mutating'方法 - 類似於Q&A:http://stackoverflow.com/ q/40811214/2976878 – Hamish

+0

你是對的!謝謝。如果你從中得出答案,我會接受。 – BlackWolf

+0

這樣的錯誤信息是一個紅色鯡魚的情況應該是[作爲編譯器錯誤提交給Swift開源項目](http://bugs.swift.org)。 – rickster

回答

1

感謝@Hamish指點我正確的方向。

原來,編譯器信息頗具誤導性。問題是每個調用mutating方法的方法本身都必須是mutating。因此,這解決了這個問題:

struct Game { 
    private let players: [UserProfile] //set in init() 
    private var scores: [Int] = [] 

    mutating func setScore(_ score: Int, playerIndex: Int) { 

     //... stuff happening ... 

     self.scores[playerIndex] = score 
    } 

    mutating func setScore(_ score: Int, player: UserProfile) { 
     guard let playerIndex = self.players.index(of: player) else { 
      return 
     } 

     self.setScore(score, playerIndex: playerIndex) 
    } 
} 

另見.sort in protocol extension is not working

+0

哇,這真是一個令人困惑的編譯器錯誤。謝謝! – ph1lb4