我已经搜索了谷歌这个答案很长时间,直到我在堆栈溢出创建了一个帐户才能提出这个问题。
如何编写一个变量来保存一个包含某个变量的类,然后再调用两次相同的函数?在代码中解释:
class Persons {
var oldName = ""
var oldAge = 0
var oldGender = ""
var name = ""
var age = 0
var gender = ""
func create(_ name:String, _ age:Int, _ gender:String) -> String {
if(age > 100) {
print("Can't create a person with an age that is over 100!")
return "Not created!"
}
if(gender == "Boy" || gender == "Girl") {
}
else {
print("Gender has to be a girl or a boy!")
return "Not created!"
}
self.name = name
self.age = age
self.gender = gender
self.oldName = name
self.oldAge = age
self.oldGender = gender
print("You just created a \(gender) called: '\(name)' with the age of: '\(age)'!")
return "Created!"
}
func modify(_ targetName:String, _ newName:String, _ newAge:Int, _ newGender:String) -> String {
if(age > 100) {
print("Can't modify a person with an age that is over 100!")
return "Not modified!"
}
if(gender == "Boy" || gender == "Girl") {
}
else {
print("Gender has to be a girl or a boy!")
return "Not modified!"
}
if(targetName != "" && targetName == self.name) {
self.name = newName
self.age = newAge
self.gender = newGender
print("You just changed \(oldName)'s gender from: \(oldGender) to: \(gender), \(oldName)'s name from: \(oldName) to: \(name) and \(oldName)'s age from: \(oldAge) to: \(age)!")
}
else {
print("Please enter a valid target name or create one!")
}
return "Modified!"
}
func delete(_ targetName:String) -> String {
if(name != "" && targetName == self.name) {
print("Deleted: \(name)!")
}
else {
print("Please enter a valid target name or create one!")
}
return "Deleted!"
}
}
var p = Persons()
p.create("Isak", 11, "Boy")
p.create("Sanne", 7, "Girl") // Here I create another person
p.delete("Isak") // But if I say delete 'Isak' it does not delete him because I created 'Sanne' above!
/*
It would work like this
p.create("Isak", 11, "Boy")
p.delete("Isak")
p.create("Sanne", 7, "Girl")
*/
请帮忙。我花了很多年才找到答案。如果您需要更多详细信息,请回复,我会尝试解释更多。
答案 0 :(得分:2)
这里的问题是您正在使用Person的单个实例。当你这样做时:
p.create("Isak", 11, "Boy")
p.create("Sanne", 7, "Girl") // Here I create another person
尽管您只是在编辑p
类Person
实例的属性,但您并未创建其他人。所以,当你删除Isak时:
p.delete("Isak")
已经没有Isak,他被改名为Sanne。
要解决此问题,您应该创建两个单独的Person实例:
var p1 = Persons()
var p2 = Persons()
p1.create("Isak", 11, "Boy")
p2.create("Sanne", 7, "Girl") // Here I create another instance of person
p1.delete("Isak")
在这种状态下,你有两个人:Sanne和Isak,你刚刚删除了,而且Sanne仍然存在且可以访问。
如果您想使用单个实例来容纳所有人,请使用以下命令:
class Person {
var oldName = ""
var oldAge = 0
var oldGender = ""
var name = ""
var age = 0
var gender = ""
func create(_ name:String, _ age:Int, _ gender:String) -> String {
if(age > 100) {
print("Can't create a person with an age that is over 100!")
return "Not created!"
}
if(gender == "Boy" || gender == "Girl") {
}
else {
print("Gender has to be a girl or a boy!")
return "Not created!"
}
self.name = name
self.age = age
self.gender = gender
self.oldName = name
self.oldAge = age
self.oldGender = gender
print("You just created a \(gender) called: '\(name)' with the age of: '\(age)'!")
return "Created!"
}
func modify(_ targetName:String, _ newName:String, _ newAge:Int, _ newGender:String) -> String {
if(age > 100) {
print("Can't modify a person with an age that is over 100!")
return "Not modified!"
}
if(gender == "Boy" || gender == "Girl") {
}
else {
print("Gender has to be a girl or a boy!")
return "Not modified!"
}
if(targetName != "" && targetName == self.name) {
self.name = newName
self.age = newAge
self.gender = newGender
print("You just changed \(oldName)'s gender from: \(oldGender) to: \(gender), \(oldName)'s name from: \(oldName) to: \(name) and \(oldName)'s age from: \(oldAge) to: \(age)!")
}
else {
print("Please enter a valid target name or create one!")
}
return "Modified!"
}
func delete() -> String {
return "Deleted!"
}
}
class Persons {
var personsDictionary = [String: Person]()
}
var persons = Persons()
var p1 = Person()
var p2 = Person()
p1.create("Isak", 11, "Boy")
p2.create("Sanne", 7, "Girl")
persons.personsDictionary[p1.name] = p1
persons.personsDictionary[p2.name] = p2
persons.personsDictionary["Isak"]?.delete()
这里我们有一个Person类(您在问题中定义但稍微改变了delete()
方法的类)和具有Dictionary [String : Person]
的Persons类。字典的关键是你的人的名字和价值就是这个人。
当我们创建一个人物实例时,我们将其存储在personsDictionary
中,而不是我们可以按人名访问该词典中的每个人,并且会返回一个可选的,我们可以调用你所定义的所有人方法
答案 1 :(得分:0)
您正尝试将模型对象用作存储库。
您只需要一个简单模型,对于简单模型,最好使用结构。这也为您提供免费的初始化
struct Person {
var name = ""
var age = 0
var gender = ""
}
注意:最好将enum用于性别......
enum Gender {
case male, female
}
struct Person {
var name = ""
var age = 0
var gender: Gender = .male
}
然后只使用数组来管理列表
let simon = Person(name: "Simon", age: 20, gender: .male)
let isak = Person(name: "Isak", age: 11, gender: .male)
var people = [simon, isak]
print(people.count) // output: 2
people.remove(isak)
print(people.count) // output: 1
let sanne = Person(name: "Sanne", age: 7, gender: .female)
people.append(sanne)
我建议您通读documentation实例,并且数组非常基本。至少阅读有关类,结构,实例化和数组的内容。
答案 2 :(得分:0)
以下是我将如何进行的开始......
首先要处理所有事情的课程:
class Person {
/// An enum for gender so that you can only ever use the permissable values.
public enum Gender {
case male
case female
}
/// An enum for the results so there are defined values to check (you could add more specific errors).
public enum Result {
case success
case failed(_: String)
}
/// A structure to hold the details of each person.
struct PersonData {
var name: String
var age: UInt
var gender: Gender
}
/// The internal list of people.
private var personList: [String: PersonData] = [:]
/// A function to create a person.
func create(_ name: String, _ age: UInt, _ gender: Gender) -> Result {
guard personList[name] == nil else {
print ("Person already created!")
return .failed("Person already created!")
}
guard age <= 100 else {
print("Can't create a person with an age that is over 100!")
return .failed("Cannot have age over 100!")
}
let person = PersonData(name: name, age: age, gender: gender)
personList[name] = person
print("You just created a \(gender) called: '\(name)' with the age of: '\(age)'!")
return .success
}
/// A function to modify a persons details in the list.
func modify(_ targetName: String, _ newName: String, _ newAge: UInt, _ newGender: Gender) -> Result {
guard let person = personList[targetName] else {
print ("Person not found in list!")
return .failed("Person not found!")
}
guard personList[newName] == nil else {
print ("Person already exists in list!")
return .failed("Person already exist in the list!")
}
if newAge > 100 {
print("Can't modify a person with an age that is over 100!")
return .failed("Cannot modify a person with an ager over 100!")
}
let oldName = person.name
let oldAge = person.age
let oldGender = person.gender
if targetName != newName {
personList.removeValue(forKey: targetName)
}
personList[newName] = PersonData(name: newName, age: newAge, gender: newGender)
print("You just changed \(oldName)'s gender from: \(oldGender) to: \(person.gender), \(oldName)'s name from: \(oldName) to: \(person.name) and \(oldName)'s age from: \(oldAge) to: \(person.age)!")
return .success
}
/// A function to delete a person from the list.
func delete(_ targetName:String) -> Result {
guard let _ = personList[targetName] else {
print ("Person not found in list!")
return .failed("Person not found in list!")
}
personList.removeValue(forKey: targetName)
print("Deleted: \(targetName)!")
return .success
}
/// A test function to print out the current list of people.
func printList() {
for (name, person) in personList {
print ("\(name) is \(person.gender) and age \(person.age)")
}
}
/// Bonus to allow you to get a persons full details using something like person[name].
subscript(name: String) -> PersonData? {
return personList[name]
}
}
现在,您可以使用它:
let people = Person()
// Create Isak.
var result = people.create("Isak", 11, .male)
// Here is how to detail with the results.
switch result {
case .success:
// Do something when successfully created.
print ("Result = Success")
case .failed(let reason):
// Do something when failed to create.
print ("Result = \(reason)")
}
// Create Sanne
result = people.create("Sanne", 7, .female)
// Print the list to check they are in there.
people.printList()
// Delete Isak from the list.
result = people.delete("Isak")
// Change Sanne's name to New Sanne and age to 8.
result = people.modify("Sanne", "New Sanne", 8, .female)
// Print the list to check what's in there.
people.printList()
// Bonus showing how to get a persons full details.
if let personData = people["New Sanne"] {
print ("\(personData.name) is \(personData.gender) and age \(personData.age)")
} else {
print ("Not Found!")
}
结果应该是:
You just created a male called: 'Isak' with the age of: '11'!
Result = Success
You just created a female called: 'Sanne' with the age of: '7'!
Sanne is female and age 7
Isak is male and age 11
Deleted: Isak!
You just changed Sanne's gender from: female to: female, Sanne's name from: Sanne to: Sanne and Sanne's age from: 7 to: 7!
New Sanne is female and age 8
New Sanne is female and age 8
我可能会更进一步,但这应该足以让你开始。
(希望这些评论可以解释它发生了什么但是如果没有随意问的话)