In Swift, how do you check if an object (AnyObject) is a string?

Tried to use:

obj.isKindOfClass(String) 

But he says Type 'String' does not conform to AnyObject protocol

So how can you determine if an object is a string or not?

The context of this question is the UIActivity method, prepareWithActivityItems, in which I need to save an activity element, but if there are several activity elements, how do you find out what exactly?

+8
string swift
source share
2 answers

Check:

 obj is String // true or false 

Convert:

 obj as? String // nil if failed to convert 

Additional binding:

 if let str = obj as? String { // success } else { // fail } 
+19
source share

I'm going to reflect a bit so that you understand what is happening.

Lines are not objects in swift. !!!

Kinda ???

Because the free bridge works, if you import the Objective-C runtime, then you can treat strings as objects ... check this:

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 fine, because we activate the bridge 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 consider it as one, it will be converted to NSString , and now it is an object. But you cannot check if the object belongs to the String class, because there is no object of type String . You must use NSString .

Of course, you should still do what Scott said in his answer using the is or as? keywords as? .

+4
source share

All Articles