官术网_书友最值得收藏!

Checking for an empty array

The count property is not the only property we can use to calculate how many items are in an array. The most commonly used property for an array is called isEmpty. This property uses the count property by checking to see whether the count is greater than 0. This method will return true or false, depending on whether there are any items within our array. Since you learned that if...else statements work well with bools, let's use this isEmpty property in an if...else statement.

Add the following to Playgrounds:

if states.isEmpty { 
  print("There are no items in the array") 
} 
else { 
  print("There are currently \(states.count) total items in our array") 
} 

Now, your code and output should look like this:

Now, our Debug panel prints the following: There are currently total 9 items in our array.

One thing to remember in programming is that occasionally, there are multiple ways of writing a piece of code. It is not shocking to meet someone who will approach the same problem differently to you. To me, this is why programming is so amazing. Ultimately, all that matters is that it works as expected, especially when you are new to programming.

All programming languages have what is known as a style guide, which is a preferred way of writing code, and it is no different in Swift. Using the preferred style means a suggested method, but even then, you will notice that most preferred methods differ on certain things. For now, you do not need to worry about different style guides, other than to know that they exist. In this book, we will follow a style that I have incorporated into my code.

Once you get comfortable, I recommend that you start to look at style guides and adapt them into your code. Knowing different styles helps you to know your options as well as to understand what others are doing with their code, even if you do not agree with how they write something. If you write your code with a defined structure or style throughout a project, it will make it easier for you to come back to your code if you, for instance, had to take a break for some reason, such as starting another project, or just taking some time off.

主站蜘蛛池模板: 醴陵市| 永丰县| 福海县| 清镇市| 那曲县| 镇安县| 聂荣县| 南阳市| 盱眙县| 新昌县| 四子王旗| 门头沟区| 沧源| 阿瓦提县| 礼泉县| 昂仁县| 潼关县| 邹城市| 溧水县| 阿拉善右旗| 临邑县| 水富县| 定远县| 萨迦县| 怀远县| 兴义市| 双辽市| 钟山县| 化隆| 鱼台县| 辰溪县| 哈尔滨市| 江油市| 肥城市| 西乌珠穆沁旗| 凤冈县| 邵阳县| 上饶县| 盐源县| 兴宁市| 和平县|