iOSエンジニアのつぶやき

毎朝8:30に iOS 関連の技術について1つぶやいています。まれに釣りについてつぶやく可能性があります。

【Swift】Protocolでdefault valueのあるパラメータを設定したい

本日もSwiftに関する小ネタです🏃‍♂️

関数でパラメータの設定を任意にする場合、下記のようにデフォルト値を設定することはよくあると思いますが、SwiftのProtocolはデフォルト値をパラメータに設定することはできません。

class Fish {
    func printFishName(name: String, location: String = "jp") {
        print("name: \(name), location: \(location)")
    }
}

こんな感じでエラーになる。

protocol FishProtocol {
    func printFishName(name: String, location: String = "jp") // Default argument not permitted in a protocol method
}

解決策

ProtocolのExtensionにデフォルト値を設定したいメソッドを設定することで実現できます。return printFishName(name: name, location: location)では、Protocolに準拠したそれぞれの具象クラスに実装されたメソッドが呼び出されます。

protocol FishProtocol {
    func printFishName(name: String, location: String)
}

extension FishProtocol {
    func printFishName(name: String, location: String = "jp") {
        return printFishName(name: name, location: location)
    }
}

てな感じで本日も以上となります🍺

参考

medium.com 

その他の記事

yamatooo.blog

yamatooo.blog

yamatooo.blog