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

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"
主站蜘蛛池模板: 开封市| 宁城县| 平顶山市| 北流市| 阜新| 邢台市| 吉首市| 元谋县| 沭阳县| 潼关县| 彭泽县| 建瓯市| 神农架林区| 新和县| 青铜峡市| 丹寨县| 宜黄县| 花垣县| 凤台县| 阿尔山市| 龙游县| 天镇县| 大姚县| 封开县| 巢湖市| 苏尼特左旗| 建阳市| 广平县| 巫山县| 黑河市| 吴忠市| 澳门| 定州市| 六安市| 文安县| 日照市| 五家渠市| 宁化县| 白沙| 台山市| 江达县|