0

Working in swift 4. I've got a function like this

func setFields<T>(_ fromView : UIView,  toObject : inout T!) -> T! 

setFields(self.view, toObject: &self.productExtended.product)

//inside ProductExtended
public var product: Product

When i call it like this i get the error:

"Inout argument could be set to a value with a type other than 'Product'; use a value declared as type '_?' instead"

Moreover if I try to call it for a field inside the ProductExtended.Product i get ambiguous context Is there a way to guarantee to the compiler that I don't change that argument's value type and i don't make it nil inside the function ?

Cyber Gh
  • 180
  • 3
  • 8
  • Is your second line meant to be `setFields` instead of `getFields`? – Chris Jun 03 '19 at 10:24
  • `Like this` is not helpful to answer the question. Please [create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Basically never declare function parameters as implicit unwrapped optional (`!`). If `toObject` must not *become `nil` in a function* declare it as non-optional (remove the exclamation mark). And why has the function an `inout` parameter **and** a return value of the same type? – vadian Jun 03 '19 at 10:32
  • This is legacy code, the function is meant to modify the incoming class and also return a reference to it. It uses implicit unwrapped optional because inside there is a lot of Reflection, and if i don't put that i get the type Optional instead of T. – Cyber Gh Jun 03 '19 at 10:51

1 Answers1

1

inout won't accept Generic type , because the reference wants to store value backs to its original value. here is the link for inout https://docs.swift.org/swift-book/LanguageGuide/Functions.html

ShyamZ_R
  • 71
  • 2
  • 3