官术网_书友最值得收藏!

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"
主站蜘蛛池模板: 东至县| 车险| 固始县| 丰都县| 双柏县| 南江县| 大余县| 汝南县| 井冈山市| 门源| 文昌市| 交口县| 彭阳县| 林周县| 隆回县| 当涂县| 邯郸市| 新宁县| 龙里县| 沧州市| 新乐市| 公主岭市| 桐梓县| 馆陶县| 固安县| 兴安盟| 绥棱县| 兖州市| 镇沅| 阿尔山市| 遂平县| 汨罗市| 武穴市| 湘潭县| 衡阳县| 卢龙县| 龙胜| 久治县| 永昌县| 伊宁县| 冷水江市|