- Learning Swift(Second Edition)
- Andrew J Wagner
- 232字
- 2021-07-16 12:33:08
Extensions
Up until this point, we had to define our entire custom type in a single file. However, it is sometimes useful to separate out part of our custom types into different files, or even just in the same file. To achieve this, Swift provides a feature called extensions. Extensions allow us to add additional functionality to existing types from anywhere.
This functionality is limited to additional functions and additional computed properties:
extension Building { var report: String { return "This building is \(self.squareFootage) sq ft" } func isLargerThanOtherBuilding(building: Building) -> Bool { return self.squareFootage > building.squareFootage } }
Note that, to define an extension, we use the extension keyword, followed by the type that we would like to extend. Extensions can also be used on an existing class, struct, or enumeration, even those defined within Swift like String. Let's add an extension to String that allows us to repeat a string any number of times:
extension String { func repeatNTimes(nTimes: Int) -> String { var output = "" for _ in 0..<nTimes { output += self } return output } } "-".repeatNTimes(4) // ----
This is just one simple idea, but it is often incredibly useful to extend the built-in types.
Now that we have a good overview of what tools we have at our disposal for organizing our code, it is time to discuss an important concept in programming called scope.
- 社交網(wǎng)絡(luò)對(duì)齊
- Web安全防護(hù)指南:基礎(chǔ)篇
- 從區(qū)塊鏈到Web3:構(gòu)建未來互聯(lián)網(wǎng)生態(tài)
- GPS/GNSS原理與應(yīng)用(第3版)
- Hands-On Full Stack Development with Spring Boot 2 and React(Second Edition)
- 物聯(lián)網(wǎng)+BIM:構(gòu)建數(shù)字孿生的未來
- HTML5 Game development with ImpactJS
- 物聯(lián)網(wǎng)時(shí)代
- SSL VPN : Understanding, evaluating and planning secure, web/based remote access
- 雷達(dá)饋線技術(shù)
- Spring 5.0 Projects
- 智慧光網(wǎng)絡(luò):關(guān)鍵技術(shù)、應(yīng)用實(shí)踐和未來演進(jìn)
- 通信十年:擁抱互聯(lián)網(wǎng)
- 網(wǎng)絡(luò)AI+:2030后的未來網(wǎng)絡(luò)
- 物聯(lián)網(wǎng)工程概論