Swift 5: How to make a Set containing Class Types (for NSXPCInterface) - swift

In Apple documentation of NSXPCInterface.setClasses(_:for:argumentIndex:ofReply:), for Swift, the first parameter is described as:
An NSSet containing Class objects —for example, [MyObject class].
Hmmm, it looks as though someone neglected to update this from Objective-C to Swift. For Swift I presume it should be something like
A Set containing Class Types
(Someone please correct my wording.) But how do you make a Set containing Class Types? The compiler will not allow me to declare a Set whose member types are not do not conform to Hashable. This makes sense because hashes are needed to maintain uniqueness among members. But Class Types in Swift do not seem to be hashable. Try this in any Swift file, or a playground…
class Foo {}
let mySet: Set<AnyHashable>
mySet.insert(Foo)
The compiler complains:
Argument type 'Foo.Type' does not conform to expected type 'Hashable'
Or, more broadly, does anyone know how to use NSXPCInterface.setClasses(_:for:argumentIndex:ofReply:) in Swift 5?

The classes you pass need to be #objc classes (and subclasses of NSObject). You'll put them into an NSSet, and then cast that to Set:
let classSet = NSSet(object: Foo.self) as! Set<AnyHashable>
This is almost certainly a bug in NSXPCInterface (it needs some kind of "refine for Swift" or possibly a shim), and I suggest opening a defect at bugreport.apple.com.

As of Swift v5.6 (perhaps earlier), you can create the set without casting:
let classSet = NSSet().adding(Foo.self)
This is because adding() is declared like this:
open func adding(_ anObject: Any) -> Set<AnyHashable>

Related

Swift work around to make `AnyObject.Type` conform to `Equatable`?

I would like to make AnyClass (AKA AnyObject.Type) conform to Equatable so that when I have an array with AnyClass elements (Array<AnyClass>), I can call remove(Element:), but this requires Element to conform to Equatable.
Since Swift 3 you could use AnyHashable as a replacement for AnyObject. It represents any value which conforms to the Equatable protocol.
Instead of
var array:[AnyObject] = []
just write
var array:[AnyHashable] = []
I don't actually think what your trying to acheive is possible, or whether you should even try to do it in this way.
Classes are generally represent real world objects, whether this is a car, a view or soemthing completely different. So it's very difficult to say is ANY custom I class I create the same as this other custom class I created.
Swift just doesn't know how to compare them, what makes them the same.
The simplest way to achieve what you want here would be to define a custom protocol/interface that does represent the generic version of the classes you will use in this application and then ensure each conforms to that and also equatable. Then you should be able to do something like:
var objs = Array<MyAppClassesProtocol>()
and also use remove(element:)

Swift dynamic type checking for structs?

I'm confused about dynamic type checking in Swift.
Specifically, I have a weirdo case where I want to, essentially, write (or find) a function:
func isInstanceOf(obj: Any, type: Any.Type) -> Bool
In Objective-C, this is isKindOfClass, but that won't work because Any.Type includes Swift structs, which are not classes (much less NSObject subclasses).
I can't use Swift is here, because that requires a hardcoded type.
I can't use obj.dynamicType == type because that would ignore subclasses.
The Swift book seems to suggest that this information is lost, and not available for structs at all:
Classes have additional capabilities that structures do not:
...
Type casting enables you to check and interpret the type of a class instance at runtime.
(On the Type Casting chapter, it says "Type casting in Swift is implemented with the is and as operators", so it seems to be a broader definition of "type casting" than in other languages.)
However, it can't be true that is/as don't work with structures, since you can put Strings and Ints into an [Any], and pull them out later, and use is String or is Int to figure out what they were. The Type Casting chapter of the Swift Book does exactly this!
Is there something that's as powerful as isKindOfClass but for any Swift instances? This information still must exist at runtime, right?
Actually you can use is operator.
Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.
Since struct can't be subclassed, is is guaranteed to be consistent when applied to instance of struct because it will check on it static type, and for classes it will query the dynamic type in runtime.
func `is`<T>(instance: Any, of kind: T.Type) -> Bool{
return instance is T;
}
This work for both, struct and class.
As already stated, is/as should work fine with structs. Other corner cases can usually be done with generic functions, something like:
let thing: Any = "hi" as Any
func item<T: Any>(_ item: Any, isType: T.Type) -> Bool {
return (item as? T) != nil
}
print(item(thing, isType: String.self)) // prints "true"
No idea if this fits your specific use case.
More generally, keep in mind that Swift (currently) requires knowing the type of everything at compile time. If you can't define the specific type that will be passed into a function or set as a variable, neither will the compiler.

Metatype of Metatype

In Swift we are able to write following construction:
class SomeClass {}
let metaMetatype: SomeClass.Type.Type = SomeClass.Type.self
Here metaMetatype does not conform to type AnyObject (SomeClass.Type does). Construction can be even longer, as long as we wish:
let uberMetatype: SomeClass.Type.Type.Type.Type.Type.Type.Type.Type.Type.Type = SomeClass.Type.Type.Type.Type.Type.Type.Type.Type.Type.self
Are this constructions have any sense? If SomeClass.Type.Type not an object, what is this, and why we able to declare it?
If SomeClass.Type.Type not an object, what is this and why we able to declare it?
I will try to dissect what you're asking.
SomeClass.Type.Type is a Metatype of a Metatype. Metatypes exist in Swift because Swift has types that are not classes. This is most similar to the Metaclass concept in Objective-C.
Lexicon.rst in the Swift Open Source Repo has a pretty good explanation:
metatype
The type of a value representing a type. Greg Parker has a good
explanation of Objective-C's "metaclasses" because Swift has types
that are not classes, a more general term is used.
We also sometimes refer to a value representing a type as a "metatype
object" or just "metatype", usually within low-level contexts like IRGen
and LLDB. This is technically incorrect (it's just a "type object"), but
the malapropism happened early in the project and has stuck around.
Why are we able to declare a type of a type of a type... and so on? Because it's a feature of the language called type metadata:
type metadata
The runtime representation of a type, and everything you can do with it.
Like a Class in Objective-C, but for any type.
Note that you can't do something like NSObject().class in Swift because class is a reserved keyword for the creation of a class. This is how you would get the type (or class in this case) of an NSObject in Swift:
let nsObj = NSObject()
nsObj.classForCoder // NSObject.Type
nsObj.classForKeyedArchiver // NSObject.Type
nsObj.dynamicType // NSObject.Type
Note that nsObj and nsObj.self are identical and represent the instance of that NSObject.
I don't see where in the Swift module or open source repo where types allow for .Type, but I'm still looking. It might have to do with the inheritance from SwiftObject, the Objective-C object all Swift classes inherit from (at least on Mac).
Type of a class is also represented in memory (it has for example their own methods). It's represented by singleton representing the Type. (It's not an instance of this type - that's something different). If you call self on a Type like this SomeClass.self you will take singleton instance representing the SomeClass Type.
For more info check this answer

any is not identical to anyObject

I've a payload getting shuttled from one part of the system to the other.
The shuttle is carrying the payload as Any, so I could carry any kind of objects including non objects like tuples, etc.
one of the parts of the system is accepting AnyObject so is the error.
I'm confused like what type to use to carry stuff around so it's compatible between all parts of the system.
Shall I make a choice and stick to one of the types, either Any or AnyObject for the system as a whole or what's the best choice for shuttling items if you are not concerned with their actual types.
we had type Object in other languages that could carry anything around, but not sure how this works in SWIFT world
or is there a casting that could work between the two? If I'm 100% convinced that the coming object is AnyObject, I could load it off from the shuttle (Any) as an AnyObject
Note to negative voters: Please help to clear up the question if it doesn't make any sense to you or help to improve this question, since I'm new to SWIFT. I need an answer not your vote.
Edit
a case where I had to do comparison between Any and AnyObject while unit testing, how would you handle such situation.
class Test {
var name: String = "test"
}
var anyObject: AnyObject = Test()
var any: Any = anyObject
//XCTAssert(any == anyObject, "Expecting them to be equal")
any == anyObject
Any will hold any kind of type, including structs and enums as well as classes. AnyObject will only hold classes. So what Any can store is a superset of what AnyObject can. No amount of casting will cram your custom structs or enums into an AnyObject.
Sometimes it seems like AnyObject is holding a struct such as a String, but it isn’t, what has happened is somewhere along the way Swift has converted your String to an NSString (which is a class so can be stored in an AnyObject).
(technically, Any is defined as something that implements 0 or more protocols, which anything does, whereas AnyObject is defined as a special protocol all classes implicitly conform to, and that is marked as an #objc protocol, so only classes can conform to it)
edit: to answer your question about comparisons – there’s no == operator for Any or AnyObject (how would it work if you equated an Any containing a String to an Any containing an Int?). You have to cast both sides back into what they really are before you can compare them using an appropriately-defined operator for that type.

What is ExistentialMetatype in Swift

This wonders me a little bit. In Swift try the following:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
println(self.superclass) //Outputs "(ExistentialMetatype)"
}
This gives the output on console to be ExistentialMetatype
Going deep into the Swift's NSObject framework it declares this superclass as a read-only computed property of type AnyClass
var superclass: AnyClass! { get }
But nowhere is there a mention of this word ExistentialMetatype. I don't know why but it reminds of Objective-C's runtime (probably its the word Metatype in it). Does anyone know anything about it?
Currently, types (instances of metatypes) get printed as unhelpful things like (Metatype) or (ExistentialMetatype). AnyClass is AnyObject.Type, a metatype. So if you try to print an AnyClass you will get this unhelpful description.
However, classes in Objective-C are objects with nice descriptions. Swift allows casting of class types into objects so they can be used in the Objective-C way. If you cast it into AnyObject first, you will see the name of the class:
println(self.superclass as AnyObject!)
If I recall correctly, what is going on is that AnyClass is a specially crafted protocol type - the protocol type that every "reference type" (class) automagically conforms to
Protocol types are sometimes called "existential types" by your friendly compiler engineers (for instance http://www.haskell.org/haskellwiki/Existential_type)
In this case, you're looking at the type object that represents such an existential type, the "metatype" as you say. Hence 'ExistentialMetatype'!