- Learning Swift
- Andrew J Wagner
- 233字
- 2021-07-16 13:54:10
Extensions
Up until this point, we had to define our entire custom type in a single file. However, it can sometimes be useful to separate out part of our custom types in different files or even just within the same file. For this, Swift provides a feature called extensions. Extensions allow us to add additional functionality to the 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) square feet" } 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 we would like to extend. This can be used on any class, struct, or enumeration, even those defined within Swift, such as String
. Let's add an extension to String
, which allows us to repeat a string any number of times:
extension String { func repeat(nTimes: Int) -> String { var output = "" for index in 0..<nTimes { output += self } return output } } "-".repeat(4) // ----
This is just one simple idea, but it can often be incredibly useful to extend the built-in types.
Now that we have a good overview of what tools we have at our disposal to organize our code, it is time to discuss an important concept in programming called the scope.
- C語言程序設(shè)計(jì)教程
- 觸·心:DT時(shí)代的大數(shù)據(jù)精準(zhǔn)營銷
- ASP.NET Core 5.0開發(fā)入門與實(shí)戰(zhàn)
- Cocos2d-x游戲開發(fā):手把手教你Lua語言的編程方法
- Android 9 Development Cookbook(Third Edition)
- JavaScript前端開發(fā)與實(shí)例教程(微課視頻版)
- C語言實(shí)驗(yàn)指導(dǎo)及習(xí)題解析
- 網(wǎng)絡(luò)爬蟲原理與實(shí)踐:基于C#語言
- jQuery開發(fā)基礎(chǔ)教程
- Oracle 18c 必須掌握的新特性:管理與實(shí)戰(zhàn)
- 學(xué)習(xí)正則表達(dá)式
- Building Dynamics CRM 2015 Dashboards with Power BI
- Troubleshooting Citrix XenApp?
- OpenCV with Python Blueprints
- Web前端測試與集成:Jasmine/Selenium/Protractor/Jenkins的最佳實(shí)踐