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

@Allen  

class Hairdresser {
  var clients = [string]()
}
  var tim = Hairdresser()
tim.clients.append("Jess")
var dave = tim
dave.clients.append("Sam")
print(tim.clients.count)
print(dave.clients.count)

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.)

   

@Allen  

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 Fernando Olivares

SPONSORED Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.

Try the book!

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.