- Swift 4 Programming Cookbook
- Keith Moon
- 284字
- 2021-07-08 10:21:29
How to do it...
If you are implementing this in a new playground, enter the following:
struct PersonName {
let givenName: String
let middleName: String
var familyName: String
func fullName() -> String {
return "\(givenName) \(middleName) \(familyName)"
}
mutating func change(familyName: String) {
self.familyName = familyName
}
}
class Person {
let birthName: PersonName
var currentName: PersonName
var countryOfResidence: String
init(name: PersonName, countryOfResidence: String = "UK") {
birthName = name
currentName = name
self.countryOfResidence = countryOfResidence
}
var displayString: String {
return "\(currentName.fullName()) - Location: \(countryOfResidence)"
}
}
You will need to go back over the previous recipes to see how these were created.
Now, let's put a number of closure types in the playground so we examine them:
// No input, no output
let printAuthorsDetails: () -> Void = {
let name = PersonName(givenName: "Keith", middleName: "David", familyName: "Moon")
let author = Person(name: name)
print(author.displayString)
}
printAuthorsDetails() // "Keith David Moon - Location: UK"
// No input, Person output
let createAuthor: () -> Person = {
let name = PersonName(givenName: "Keith", middleName: "David", familyName: "Moon")
let author = Person(name: name)
return author
}
let author = createAuthor()
print(author.displayString) // "Keith David Moon - Location: UK"
// String inputs, no output
let printPersonsDetails: (String, String, String) -> Void = { givenName, middleName, familyName in
let name = PersonName(givenName: givenName, middleName: middleName, familyName: familyName)
let author = Person(name: name)
print(author.displayString)
}
printPersonsDetails("Kathyleen", "Mary", "Moon") // "Kathleen Mary Moon - Location: UK"
// String inputs, Person output
let createPerson: (String, String, String) -> Person = { givenName, middleName, familyName in
let name = PersonName(givenName: givenName, middleName: middleName, familyName: familyName)
let person = Person(name: name)
return person
}
let melody = createPerson("Melody", "Margaret", "Moon")
print(melody.displayString) // "Melody Margaret Moon - Location: UK"
推薦閱讀
- Visual C++程序設(shè)計學習筆記
- Design Principles for Process:driven Architectures Using Oracle BPM and SOA Suite 12c
- Power Up Your PowToon Studio Project
- 軟件界面交互設(shè)計基礎(chǔ)
- Mastering SVG
- Python程序設(shè)計(第3版)
- Java設(shè)計模式及實踐
- 從Java到Web程序設(shè)計教程
- 51單片機C語言開發(fā)教程
- C++寶典
- ElasticSearch Cookbook(Second Edition)
- Python爬蟲、數(shù)據(jù)分析與可視化:工具詳解與案例實戰(zhàn)
- Clean Code in C#
- 工業(yè)機器人離線編程
- Scrapy網(wǎng)絡(luò)爬蟲實戰(zhàn)