[SOLVED] How to define a variable with multiple specific custom types ? (in Swift)

Issue

Hi guys as you may know sometimes, it would be so handy and clean if we could define a variable which can store multiple variable types. this operation
is easily possible if we use “Any” instead of our type name.
for example :

var a : Any     // defines a variable with ability to store all types except a nil
var b : Any?    // defines a variable with ability to store all types including nil
var c : String  // a variable storing only and only a String value
var d : String? // a variable such as "c" , but also includes nil too

in the first two ones we can store all {Int , String , Float & etc.}. also in the third and fourth one we can store String values while we can’t store others such as “Int” or “Float” .
but what if in some cases we would like to have a variable which can store custom Types ? for example i want a variable which can store an “Int” value , can store a “String” one, but can not store “Float”s ?

var e : only(String and Int)
// some code like above, or even below :
var f : Any but not Float

is there any idea ? is there any solution please ?

thanks dudes

Solution

Seems like you need to use protocols.

Something like:

protocol CustomType {
    // your definitions ...
}

extension String: CustomType {}
extension Int: CustomType {}

let customType1: CustomType = "string"
print(customType1)
let customType2: CustomType = 0
print(customType2)

// Error: Value of type 'Double' does not conform to specified type 'CustomType'
// let customType3: CustomType = 0.0

In this case, values of CustomType type will only accept String and Int types (because of the protocol conformance).

Answered By – eMdOS

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published.