What is the type of Swift?

I want to pass an array of type types to a function, but I'm not sure what a Swift type is.

Let's say I have two classes: MyClass and AnotherClass. I need an array like this [MyClass, AnotherClass]. What will be the type of array?

+4
source share
4 answers

It will have a type AnyClassthat is basic for all types of objects.

func checkClassTypes(types: [AnyClass]) {
  types.forEach { type in
    // Your custom classes don't necessarily have to subclass from NSObject.
    print(type is NSObject.Type)
  }
}

checkClassTypes([MyClass.self, AnotherClass.self])
+1
source

If you need to contain only class types, it AnyClasswill work:

class MyClass {
    //...
}
class AnotherClass {
    //...
}
let classTypes: [AnyClass] = [MyClass.self, AnotherClass.self]

If you want to include some types of values, you may need to use Anyeither Any.Type:

let types: [Any] = [Int.self, String.self, MyClass.self, AnotherClass.self]
let anyTypes: [Any.Type] = [Int.self, String.self, MyClass.self, AnotherClass.self]

, AnyClass, Any Any.Type, . , .

+1

, Swift, Swift . Swift , , float, string, integer .. , Swift , , Swift , ( ), Swift , , ( ).

, , . Swift . , ( ). . , Type /, , , , , . , , . , , Swift Apple. iBooks Store.

, [MyClass, AnotherClass], . AnyObjects , AnyClass,

myArray = [AnyClass]()

/ , , Double, String .

. , . , . ,

if let myObject = myArray[2] as? myClass { do something }

, xcode .

, .

Regards, MacUserT

0
source

I assume that you really want to create an array of instances of two classes, not an array of class definitions. If so, you will create an array of Anyor AnyObjectrather than AnyClass.

class MyClass {
}

class OtherClass {
}

let m = MyClass()
let o = OtherClass()

let array1 = [m, o] as [Any]
// or
let array2 = [m, o] as [AnyObject]
-1
source

Source: https://habr.com/ru/post/1653566/


All Articles