Tried using:
obj.isKindOfClass(String)
But it says Type 'String' does not conform to protocol 'AnyObject'
So how can you tell if an object is a string or not?
The context of this question is the UIActivity method, prepareWithActivityItems, in which I need to save the activity item, but if there are multiple activity items, how do you figure out which is which?
Type casting in Swift is implemented with the is and as operators. is is used to check the type of a value whereas as is used to cast a value to a different type. Consider the following classs LivingBeing and two subclasses of LivingBeing named Human and Animal .
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's not.
You use AnyObject when you need the flexibility of an untyped object or when you use bridged Objective-C methods and properties that return an untyped result. AnyObject can be used as the concrete type for an instance of any class, class type, or class-only protocol.
Check:
obj is String // true or false
Convert:
obj as? String // nil if failed to convert
Optional binding:
if let str = obj as? String {
// success
} else {
// fail
}
I'm going to go off on a bit of a tangent so you understand what is going on.
Strings are not objects in swift. !!!
Kinda. ???
Because of the way toll-free bridging works... if you import the Objective-C runtime then you can treat strings as an object... check this out:
This code will not compile at all:
// Playground - noun: a place where people can play
// import Foundation
var foo: AnyObject = "hello"
^ Type 'String' does not conform to protocol 'AnyObject'
But if I uncomment the Foundation framework, then it compiles perfectly fine, because we're activating bridging between String and NSString:
// Playground - noun: a place where people can play
import Foundation
var foo: AnyObject = "hello" // We're all good here!
And if you want to check if foo is a string... you can do this:
import Foundation
var foo: AnyObject = "hello"
foo.isKindOfClass(NSString) // this returns true
So... string is not an object but if you treat it as one it will be converted into an NSString
and now it is an object. But you can't check if an object belongs to the String
class, because there is no such thing as a String
object. You have to use NSString
.
Of course, you should still be doing what Scott said in his answer, by using the is
or as?
keywords.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With