- 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"
推薦閱讀
- 高手是如何做產(chǎn)品設(shè)計(jì)的(全2冊(cè))
- Modular Programming with Python
- 企業(yè)級(jí)Java EE架構(gòu)設(shè)計(jì)精深實(shí)踐
- Spring技術(shù)內(nèi)幕:深入解析Spring架構(gòu)與設(shè)計(jì)
- PyTorch Artificial Intelligence Fundamentals
- 網(wǎng)頁(yè)設(shè)計(jì)與制作教程(HTML+CSS+JavaScript)(第2版)
- Internet of Things with the Arduino Yún
- Functional Programming in JavaScript
- TypeScript圖形渲染實(shí)戰(zhàn):基于WebGL的3D架構(gòu)與實(shí)現(xiàn)
- 人人都懂設(shè)計(jì)模式:從生活中領(lǐng)悟設(shè)計(jì)模式(Python實(shí)現(xiàn))
- Learning Data Mining with R
- Learning Three.js:The JavaScript 3D Library for WebGL
- 動(dòng)手打造深度學(xué)習(xí)框架
- HTML5移動(dòng)前端開(kāi)發(fā)基礎(chǔ)與實(shí)戰(zhàn)(微課版)
- Learning Cocos2d-JS Game Development