-
-
Save jcmendez/442ef92be9358a9eab256275c254c54e to your computer and use it in GitHub Desktop.
Sample code for the question http://stackoverflow.com/questions/37365594/recommended-way-to-override-a-method-on-a-constrained-extension-in-swift-avoidi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum Suit {} | |
enum Rank: Int {} | |
// In the example, let's say the Card is CustomStringConvertible so I can leverage all the external code | |
// that prints stuff, and depends on using the var description | |
struct Card : CustomStringConvertible { | |
var rank: Rank | |
var suit: Suit | |
var description : String { | |
return rank.simpleDescription() + suit.simpleDescription() | |
} | |
} | |
// Define a protocol for specializing Arrays of Cards | |
protocol _CardType {} | |
extension Card: _CardType {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typealias Deck = [Card] | |
// Using swift's constrained extensions | |
extension Array where Element : _CardType { | |
// This is the method that would not compile if I try to use override | |
// override var description: String { | |
var description: String { | |
return "Deck: " + self.map { "\($0)" }.joinWithSeparator(",") | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CardsTests: XCTestCase { | |
var deck : Deck! | |
override func setUp() { | |
super.setUp() | |
deck = Deck.standard() // Create a standard poker deck | |
} | |
func testBasicDeck() { | |
// Here you get the error Ambiguous use of description | |
print(deck.description) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment