Swift generics issue: generic parameter could not be inferred
This is the wrong signature:
public func getLoginInfo(loginInfoClass: LoginInfoBase.Type, completionHandler: @escaping (Swift.Result<LoginInfoBase, Error>) -> Void)
You mean this:
public func getLoginInfo<T: LoginInfoBase>(loginInfoClass: T.Type, completionHandler: @escaping (Swift.Result<LoginInfoBase, Error>) -> Void)
^^^^^^^^^^^^^^^^^^ ^
You need to pass a concrete type to getLoginInfo
that conforms to LoginInfoBase. Not just any subtype. This matches your genericQuery
method.
You should then modify your call to genericQuery as:
genericQuery(urlString: "\(baseURL)/users/get_login_info/",
method: .get,
params: nil,
decodable: T.self) { ... } // use T.self here.
For more details, see Alexander's link.
Swift Generics issue
With Swift, we'll need to think whether there's a function that can do the trick -- outside the methods of a class.
Just like in our case here:
contains(theArray, theItem)
You can try it in a playground:
let a = [1, 2, 3, 4, 5]
contains(a, 3)
contains(a, 6)
I discover a lot of these functions by cmd-clicking on a Swift symbol (example: Array) and then by looking around in that file (which seems to be the global file containing all declarations for Swift general classes and functions).
Here's a little extension that will add the "contains" method to all arrays:
extension Array {
func contains<T: Equatable>(item: T) -> Bool {
for i in self {
if item == (i as T) { return true }
}
return false
}
}
Swift generics and protocols issue
Sad to say, Swift doesn't perform implicit casting like that. As of now, you have to re-Box()
the value.
func fetchComicsViewModel() -> Box<ComicViewModel> {
return Box(sampleComics().value)
}
A type mismatch issue with generic methods
Is this what you wanted ?
struct One: Codable {}
struct Two: Codable {}
func test(ofType: Codable.Type) {
print(ofType)
}
var array = Array<Codable.Type>()
array.append(One.self)
array.append(Two.self)
array.forEach { (type) in
print(type)
} // Outs: One\nTwo
test(ofType: One.self) // out: One
test(ofType: Two.self) // out: Two
array.forEach { (type) in
test(ofType: type)
} // Outs: One\nTwo
Related Topics
What Is Trailing Closure Syntax in Swift
Naming Convention for Optional Binding
Pattern Match and Conditionally Bind in a Single Switch Statement
Change Time Interval in Skaction.Waitforduration() as Game Goes On
Swift Performseguewithidentifier Shows Black Screen
How to Declare a Class Level Function in Swift
Does Swift Compile to Native Code
Appearance Proxies/Ui_Appearance_Selector in Swift
How to Avoid That My Swift Async Method Runs on the Main Thread in Swiftui
Is There a Preferred Technique to Prohibit Pasting into a Uitextfield
Swift - Force Synchronous Execution of Work and Subsequent UI Rendering