gpt4 book ai didi

ios - 使用 .append 到类数组时出现 Swift "Extra Argument in Call"错误

转载 作者:行者123 更新时间:2023-11-28 06:34:55 25 4
gpt4 key购买 nike

我最近才开始学习 Swift,作为我的一个程序的一部分,我一直在尝试维护一个类实例数组,并使用 .append 将新实例添加到类数组中。

但是,当尝试将新的类实例附加到数组时,会出现“Extra Argument in Call”错误。我已经确定为所有变量指定数据类型以确保不会出现数据类型冲突的编译器错误,但这仍然没有解决问题。

代码如下:

import UIKit

var personMgr: personManager = personManager()

class person{

var name:String = "Default"
var description:String = "Default"
var presentIdeasDict:[Int: String] = [
0: "nil"
]
var presentLinkDict:[Int: String] = [ //Use same key for name of present idea and link for the present
0: "nil"
]

}

class personManager{

var people = [person]()

func addPerson(name: String, description: String){
people.append(person(name: name, description: description, presentIdeasDict: [0: "nil"], presentLinkDict: [0: "nil"]))
}

}

错误提示“Extra argument 'name' in the call in the line:

people.append(person(name: name, description: description, presentIdeasDict: [0: "nil"], presentLinkDict: [0: "nil"]))

最佳答案

您需要为“person”类创建一个初始化器。

请注意,您也可以为初始化参数设置默认值。这样您就不必在多个地方使用默认值(您甚至可以在其他初始化程序中省略默认参数)。

另请注意,按照惯例,类名应大写。

例子:

class Person {

var name:String
var description:String
var presentIdeasDict:[Int: String]
var presentLinkDict:[Int: String]

init(name: String = "Default", description: String = "Default", presentIdeasDict: [Int: String] = [0: "nil"], presentLinkDict: [Int: String] = [0: "nil"]) {
self.name = name
self.description = description
self.presentIdeasDict = presentIdeasDict
self.presentLinkDict = presentLinkDict
}

}

class PersonManager {

var people = [Person]()

func addPerson(name: String, description: String) {
people.append(Person(name: name, description: description))
}

}

关于ios - 使用 .append 到类数组时出现 Swift "Extra Argument in Call"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39327801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com