Swift 新手。对类(class)有一定的了解。我有一个 getSomething() 函数,该函数应该返回从字典附加的键值数组(不是值本身,而是它们的键)。但是,我的函数只返回 nil
public class MyClass {
private var somethingA : String
private var somethingB : String
private var somethingC : Int
// A dictionary
// For example, if I add a fruit, color and price
// ["Apple":["red":5]]
private var complexes:[String:[String:Int]] = [String:[String:Int]]();
init() {
self.somethingA = "";
self.somethingB = "";
self.somethingC = 0;
self.complexes = [somethingA:[somethingB:somethingC]];
}
// Adds a string to the dict complexes
// For example, ["Apple] = ["", 0]
public func addSomething(somethingAA : String) {
self.somethingA = somethingAA;
self.complexes[somethingAA] = [self.somethingB : self.somethingC];
}
// Adds a whole entry to the dict complexes
// For example, ["Apple"] = ["red": 5]
public func addComplex(somethingAA: String, complex:(somethingBB: String, somethingCC: Int)) {
self.somethingA = somethingAA
self.somethingB = complex.somethingBB
self.somethingC = complex.somethingCC
complexes[somethingAA] = [complex.somethingBB: complex.somethingCC]
}
// My Problem: only returns nil
public func getSometing() -> [String]?{
var myArray:[String]? = nil;
let keys = Array(complexes.keys);
for key in keys { myArray?.append(key); } // This may be the line of code that isn't properly working
return myArray;
}
}
我的测试文件:
var sampleObject:MyClass;
sampleObject = MyClass();
sampleObject.addSomething(somethingAA: "Apple");
sampleObject.addSomething(somethingAA: "Orange");
print(sampleObject.getSomething());
我的 getSomething()
函数仅打印 nil
,这意味着它没有将正确的 keys
附加到 myArray
不太清楚为什么。由于这是我使用 Swift 的头几天,所以还没有真正使用或熟悉 nils
,但我在 Java 和 C# 中使用过 nulls
。 nils
等同于 nulls
吗?
我想要的正确输出应该返回如下:
["Apple", "Orange"] // not necessarily in order
最佳答案
您尚未初始化数组。所以事情应该是这样的:
public func getSometing() -> [String]?{
var myArray = [String]();
let keys = Array(complexes.keys);
for key in keys { myArray?.append(key); } // This may be the line of code that isn't properly working
return myArray;
}
关于ios - Swift - 函数在附加字典中的键值后仅返回 nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49147370/