Swift: Strings aren’t objects

Today as I was working with Swift – updating last week’s article on generics – I learned something new. Strings aren’t objects – they’re structures.

Strings are structs! (screenshot)

When I saw this, I thought, “wait a minute… does this mean that String doesn’t have any methods?” Well, what do you think?

From The Swift Programming Language:

Classes and structures are general-purpose, flexible constructs that become the building blocks of your program’s code. You define properties and methods to add functionality to your classes and structures… [emphasis mine]

So structures in Swift can have methods. And if you look at the definition of String, you’ll see that it still has all of our favorite methods: isEmpty, uppercaseString, lowercaseString, hasPrefix, hasSuffix, and more…

So even though Strings aren’t objects in Swift, they can do a lot of the things we’ve come to expect them to do. But they’re not defined in a class, which means you can’t subclass String. And that’s probably a good thing. :)

The fact that Strings aren’t objects also means that they can’t be represented by AnyObject, since AnyObject can only represent class types. If you want to represent any type, including non-class types, you can use Any. So we could do this:

let things: [Any] = ["banana", 3]

But that wouldn’t work with [AnyObject] instead of [Any] since neither String nor Int is defined in a class – they’re not objects, they’re structs, even though they have methods. Yes, to reiterate, structures in Swift have methods.

And so, in conclusion…

Strings aren’t objects in Swift, and they can’t be represented with AnyObject – but they can be represented by Any. Strings are structs, and they have all the methods we’re used to seeing – because in Swift, structs can have methods.

Keep learning Swift with the 5-Part Guide to Getting Started, plus my weekly articles designed to help you become a better iOS developer.

Further reading

If you’re interested in the differences between classes and structures, as well as how you might decide between a class or a structure for your data type, I’d suggest reading the chapter on Classes and Structures in The Swift Programming Language. One major reason you might choose a class: when you want to use or allow for inheritance.