NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

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 Paw

SPONSORED Use Paw to build, test and describe web APIs. Paw has a lightning fast native macOS interface to compose requests, collaborate in real-time on API specs, and generate client code for your applications. You can import and export API definitions.

Discover Paw for Mac

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

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

Not logged in

Log in
 

Link copied to your pasteboard.