2015-01-13 3 views
5

선택적 인수를 받거나 무시할 수 있도록 프로토콜 함수를 어떻게 설정할 수 있습니까? 당신이 "방법"을 선포의 에, 모든프로토콜 메서드/함수에서 기본 인수를 무시하고 인수를 무시하십시오.

//Goal: Default forRound should be 0 if none provided 
class OnlineGame : Game { 
    func modeName(forRound: Int = 0) -> ModeName { 
     //Some code 
    } 
} 

//Goal: I don't care about the forRound value here 
class OfflineGame : Game { 
    func modeName(_ forRound: Int) -> ModeName { 
     //Some code 
    } 
} 

답변

0

첫째, 및 the first parameter of "method" has no external name by default :이 2 개 특별한 클래스와

protocol Game { 
    func modeName(forRound: Int) -> ModeName 
} 

:

나는이 프로토콜을 가지고있다. 이 메서드의 첫 번째 매개 변수의 경우에도 OnlineGame 경우

class SomeGame: Game { 
    func modeName(forRound: Int) -> ModeName { 
     // ... 
    } 
} 

let game: Game = SomeGame() 
let modeName = game.modeName(1) // not `game.modeName(forRound: 1)` 

, if the parameter has default value, it has external name automatically : 그래서 여기에 매우 정상 경우 코드입니다. 당신은 _ 등의 명시 적 외부 이름으로 그 동작을 무시할 수 있습니다 : 귀하의 답변에 대한

class OfflineGame : Game { 
    func modeName(_: Int) -> ModeName { 
     //Some code 
    } 
} 
+0

감사합니다 : 당신의 OfflineGame 경우

class OnlineGame : Game { func modeName(_ forRound: Int = 0) -> ModeName { //Some code } } 

, 당신은 _ 내부 이름 등으로 매개 변수를 무시할 수 있습니다. OnlineGame 클래스에 쓴 것처럼 함수를 설정하면 나는'OnlineGame'에 여전히 문제가 있습니다.'function.modeName()'을 호출 할 수 없습니다 :'func modeName (_ forRound : Int = 0) -> ModeName' – Kalzem

+0

니스. 이것은 나를 위해 일했다. 얼마 전에 내 첫 시도에서 나는 분명히 약간의 잘못을 저질렀습니다. 감사! –

+0

@BabyAzerty 어떻게'game' 변수를 선언합니까? 그것이'let game : Game = OnlineGame()'이라면 컴파일러는'OnlineGame' 클래스의 인스턴스라는 것을 모르기 때문에'.modeName()'을 직접 호출 할 수 없습니다. – rintaro

관련 문제