UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

2      

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

2      

@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!

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free 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.