NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

Why property value less a [] result changed 2 to 7?

Forums > Swift


class Hairdresser {
  var clients = [string]()
  var tim = Hairdresser()
var dave = tim

the result: 2 2

when I change the property value from [string] () to string ()

the result shows: 7 7


Because [String]() is an array of String values. So when you call append() on it, you add values to the array. In your code, you called append() twice, so the final count is 2, as that's how many items are in your array.

On the other hand String() is a single String value. When you call append() on it, you are adding onto the end of the String. So when you call append("Jess") then append("Sam"), you are adding Strings of length 4 and 3, respectively. 4 + 3 is, of course, 7, which is the result you get at the end when you check count.

So in the first example, you end up with ["Jess", "Sam"] whereas in the second you end up with "JessSam".

(And just an FYI: The code as you've posted it here actually won't compile, since you lowercased [string](). The type name is String with a capital S.)



That really makes sense. At the begining I thought that's because the previous codes interrupted the result , latter I tried on another playground It's the same result. So it came to me that it might be the way the String counts the letter changed with []. Never thought that deep about Array of string values.. Thanks again bro!


Hacking with Swift is sponsored by Essential Developer

SPONSORED From January 26th to 31st you can join a FREE crash course for iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a senior developer!

Save your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.