- 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"
推薦閱讀
- 造個小程序:與微信一起干件正經事兒
- JavaScript語言精髓與編程實踐(第3版)
- PyTorch自然語言處理入門與實戰
- 精通搜索分析
- SAS數據統計分析與編程實踐
- SQL Server 2016數據庫應用與開發習題解答與上機指導
- 信息技術應用基礎
- Web Development with MongoDB and Node(Third Edition)
- Access 2010數據庫應用技術(第2版)
- 響應式架構:消息模式Actor實現與Scala、Akka應用集成
- Modern C++ Programming Cookbook
- Python 快速入門(第3版)
- Deep Learning for Natural Language Processing
- Drupal 8 Development Cookbook(Second Edition)
- GO語言編程從入門到實踐