我已经创建了achievementArray
类AchievementObject
并附加了所有必要的值。出于测试目的,我对第一个索引进行了硬编码。我想将这个数组传递给我的AchievementDatabase
类,这样我就可以检查数组的大小。 (我希望在集成我的实际数据库之前让客户端工作)。
我收到此错误:
无法将
AppDelegate.AchievementObject.Type
类型的值转换为预期的参数类型AppDelegate.AchievementObject
这是我的相关代码,全部在AppDelegate.swift
文件中:
var achievementArray = [AchievementObject]();
achievementArray.append(AchievementObject(achievementID: -1, achievementName: "achievementName", achievementDescription: "achievementDescription")); //Append to allow subscripting
achievementArray[1].achievementID = 1;
achievementArray[1].achievementName = "Hello World!";
achievementArray[1].achievementName = "Be Born!";
debugPrint(achievementArray[1].achievementName); //Returns Hello World!
var achievementDB = AchievementDatabase(achievementArray: AchievementObject); *<-- Error Here*
class AchievementObject {
var achievementID: Int;
var achievementName: String;
var achievementDescription: String;
init(achievementID: Int, achievementName: String, achievementDescription: String) {
self.achievementID = achievementID;
self.achievementName = achievementName;
self.achievementDescription = achievementDescription;
return;
}
class AchievementDatabase {
//Act as a local database storage until connection is made
var numAchievements: Int = 1; //Will change to achievementArray.count();
init(achievementArray: AchievementObject) {
for i in 1...numAchievements {
debugPrint("i: \(i)");
//var achievement = AchievementObject(id:i); //
}
}
答案 0 :(得分:1)
我认为您的代码中有一些更改。无论如何
主要问题是AchievementDatabase
获得了AchievementObject
,但实际上您需要一个数组,那么您应该使用符号[AchievementObject]
。
所以你可能想要遵循这个重构:
<强>测试强>
var achievementArray = [AchievementObject]()
achievementArray.append(AchievementObject(achievementID: -1, achievementName: "achievementName", achievementDescription: "achievementDescription"))
achievementArray[0].achievementID = 1
achievementArray[0].achievementName = "Hello World!"
achievementArray[0].achievementName = "Be Born!"
let achievementDB = AchievementDatabase(achievementArray: achievementArray)
print(achievementDB.achievementArray.count)
<强>型号:强>
class AchievementObject {
var achievementID: Int
var achievementName: String
var achievementDescription: String
init(achievementID: Int, achievementName: String, achievementDescription: String) {
self.achievementID = achievementID
self.achievementName = achievementName
self.achievementDescription = achievementDescription
}
}
class AchievementDatabase {
var achievementArray: [AchievementObject]
init(achievementArray: [AchievementObject]) {
self.achievementArray = achievementArray
achievementArray.enumerated().forEach { (index, value) in
print("index: \(index), value: \(value.achievementName)")
}
}
}
<强>观察强>:
;
AchievementDatabase
正在获取一个对象,但您应该传递一个类似[AchievementObject]
for i..n
,很好的解释here。 achievementArray.first
AchievementObject
应该是一个结构,而不是一个类。那你甚至不需要提供init。 AchievementObject
的值在设置后不会更改,请将所有属性更改为var。 答案 1 :(得分:-1)
尝试
var achievementDB = = AchievementDatabase(achievementArray: achievementArray))