Search code examples
swiftios8assert

cannot convert expression type void to type integer in Swift using XCTAssertEqual


I am very new to the Swift language and XCode. Have a error message from this code:

Class Deck

class Deck {

    var decks : Integer = 0

    init () {
       decks = 1
    }

    init (amountOfDecks : Integer){
       decks = amountOfDecks
    }

    func getAmountOfCards() -> Integer {
        return 0
    }

}

Test Class

import XCTest
import helloWorldv2

class helloWorldv2Tests: XCTestCase {

    override func setUp() {
        super.setUp()
    }

    override func tearDown() {
        super.tearDown()
    }

    func testDeckConstructor() {
        var deck = Deck(amountOfDecks: 1)
        var amount : Integer = deck.getAmountOfCards()
        let expected : Integer = 52

        // ERROR: Cannot convert the expression type 'void' to type 'integer'
        XCTAssertEqual(expected, amount)
    }        
}

I set the two variables to type Integer so don't understand why I cant compare the two values...


Solution

    1. the Type you should be using is Int (Integer is a protocol, not a Type, and there is not an implementation in Swift for == that accepts arguments conforming to the Integer protocol)

    2. specifying the Type in the way that you are doing it is unnecessary, thanks to Swift's "type inference" - when you declare and assign a value to a variable, it will automatically give that variable the same Type as the value that is being assigned to it (and literal integers in Swift are typed as Int by default)... so let expected = 52 will automatically give your expected constant the Type Int without you having to declare it as such