-1

I would like to defined a variable with multiple type, but i fail in this case. I want to use it as UITextfield or UIButton in other way. Please help

struct FieldsModel {
    let input: [UITextField, UIButton]
}
wong john
  • 55
  • 4
  • try let input: [Any] – Muhammad Waqas Feb 15 '22 at 06:36
  • I want to use some UITextField or UIButton function when passing input into my function. But i dont want to cast it to Textfield or button – wong john Feb 15 '22 at 06:40
  • 1
    A variable can't have multiple types. Perhaps you could explain more clearly what you are trying to achieve. `UIKit` types are classes, so there is an inheritance hierarchy that you may be able to use, or perhaps you could use an `enum` with associated values, but the chances are at some point you are going to need to cast to the concrete type in order to access specific properties and methods. – Paulw11 Feb 15 '22 at 06:46
  • I can defined one more field in Struct. but a lot of items dont use this field. it will be a lot of null – wong john Feb 15 '22 at 06:48
  • Is `input` supposed to be an array or a single object? – Joakim Danielson Feb 15 '22 at 07:32

2 Answers2

1

You can give only 1 type to a variable . The variation in your question is not valid.You can't assing 1..n datatype to a variable . You can use property of the structure generic . Maybe you want something like that

struct FieldsModel<T> {
    let input: [T]
}

let structWithButton = FieldsModel<UIButton>(input: [yourButtons])
let structWithTextField = FieldsModel<UITextField>(input: [yourTextfield])
Omer Tekbiyik
  • 4,255
  • 1
  • 15
  • 27
  • While it isn't clear what the OP is actually trying to do, generics probably aren't a great fit since generic types are not covariant – Paulw11 Feb 15 '22 at 06:53
  • What about restricting what T can be? – Joakim Danielson Feb 15 '22 at 07:31
  • That is what the other answer does, but you will still likely have a problem with covariance. You can't have a function that accepts `FieldsModel` as a parameter or a property of type `FieldsModel`. `FieldsModel` and `FieldsModel` are distinct types. – Paulw11 Feb 15 '22 at 07:40
0
struct FieldsModel<Control: UIControl> {
  let input: Control
}

let buttonModel: FieldsModel<UIButton>
let textFieldModel: FieldsModel<UITextField>
  • While it isn't clear what the OP is actually trying to do, generics probably aren't a great fit since generic types are not covariant. What benefit do you get using a generic container over the superclass `UIControl`? – Paulw11 Feb 15 '22 at 06:53
  • You might be right; that's why I just posted the code and figured we'd get feedback if the OP wants to work through it. But constrained extension of `Control` may solve the problem "i dont want to cast it to Textfield or button". –  Feb 15 '22 at 17:16