Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift can't call isKindOfClass with String

Tags:

string

ios

swift

I have

let fieldValue: AnyObject?

if I want to check if it's NSString, it's ok:

fieldValue!.isKindOfClass(NSString)

But when I try to check if it's String, it give the error:

fieldValue!.isKindOfClass(String)
Cannot call value of non-function type '((AnyClass) -> Bool)!'
like image 218
Paul T. Avatar asked Aug 26 '15 06:08

Paul T.


People also ask

What is a string in Swift?

A string is a series of characters, such as "hello, world" or "albatross". Swift strings are represented by the String type. The contents of a String can be accessed in various ways, including as a collection of Character values. Swift’s String and Character types provide a fast, Unicode-compliant way to work with text in your code.

Can we access characters of a string through brackets in Swift?

We can see that we can access characters of a string through the brackets as it was with the array. It may be disappointing that characters at the given positions are read-only in Swift, so we can't write the following:

What are Unicode scalars in Swift?

In Swift, Character s and String s are represented by Unicode Scalars, a 21-bit representation of one character. It can be, for example, "a", digits, special characters or emojis. We get this value or values from the unicodeScalars property of a Character or String.

Why can’t I Index a string in Swift?

For this reason, Swift strings can’t be indexed by integer values. Use the startIndex property to access the position of the first Character of a String. The endIndex property is the position after the last character in a String. As a result, the endIndex property isn’t a valid argument to a string’s subscript.


2 Answers

isKindOfClass() works only with classes that are subclass of NSObject.

You can use fieldValue is String.

if fieldValue is String {
  // do something with string
}
like image 194
tuledev Avatar answered Sep 28 '22 08:09

tuledev


use 'is'

if fieldValue is String {
//
}
like image 44
Prabhu.Somasundaram Avatar answered Sep 28 '22 06:09

Prabhu.Somasundaram