问题
I'm baffled by something I've run into a couple of times. I sometimes get errors similar to the following
Cannot convert value of type 'Foo!' to expected argument type 'Foo!
'
I've searched SO, but haven't really found anything that explains why Foo! isn't the same as Foo!.
Here's an example:
// FooViewModel.swift
class FooViewModel: BaseViewModel {
fileprivate var foo: Foo!
fileprivate var bar: Bar = Bar()
init!(model: Foo!) {
super.init()
foo = model
}
override init() {
super.init()
}
func setFooModel(_ model: Foo!) {
self.foo = model
}
func getFooModel() -> Foo! {
return self.foo
}
func getBar() -> Bar {
return bar
}
func getBlah() -> String {
return "Blah"
}
}
Here is the unit test that generates the error:
import XCTest
@testable import WooHoo
class FooViewModelTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testGetBar() {
var foo = Foo()
let vm = FooViewModel()
// The following line generates the error
vm.setFooModel(foo)
XCTAssertEqual("Tell us your Foo for the Bar program.", vm.getBlah())
}
}
I've tried a number of variations for vm.setFooModel(foo)
to no avail, e.g. vm.setFooModel(foo!)
or declaring foo as var foo: Foo! = Foo()
.
edit: Note that the code above is for illustrating the issue I'm running into and is not the operational code.
回答1:
I figured this out. My view model was part of the tests target. After I set it to the run target only, the issue resolved. FYI.
来源:https://stackoverflow.com/questions/46167309/cannot-convert-value-of-type-foo-to-expected-argument-type-foo