有什么方法可以简化这个:
var unloadedImagesRows = [String:[Int]]()
private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
if unloadedImagesRows[forLocation] == nil {
unloadedImagesRows[forLocation] = [Int]()
}
unloadedImagesRows[forLocation]!.append(row)
}
没有Swift有一种简单的方法来检查nil
,如果是,创建一个新对象,所有后续使用都引用该对象?
答案 0 :(得分:8)
您可以将其简化为一行:
private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
unloadedImagesRows[forLocation] = (unloadedImagesRows[forLocation] ?? []) + [row]
}
答案 1 :(得分:2)
您可以为nil检查创建一个帮助程序运算符,并像下面一样使用它。
infix operator ?= { associativity left precedence 160 }
func ?=<T: Any>(inout left: T?, right: T) -> T {
if let left = left {
return left
} else {
left = right
return left!
}
}
如果为空
,您可以像unloadedImagesRows[forLocation] ?= [Int]()
一样使用它
var unloadedImagesRows = [String:[Int]]()
private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
unloadedImagesRows[forLocation] ?= [Int]()
unloadedImagesRows[forLocation]!.append(row)
}
addToUnloadedImagesRow(1, forLocation: "This is something")
print(unloadedImagesRows) // "["This is something": [1]]\n"
答案 2 :(得分:2)
如果您想避开if
或guard
,可以尝试nil coalescing operator (??)。
private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
var rowsForLocation = unloadedImagesRows[forLocation] ?? [Int]();
rowsForLocation.append(row)
unloadedImagesRows[forLocation] = rowsForLocation
}
注意: 这可能效率不高,因为您必须将数组重新分配给字典。我不确定这是否会产生数组的完整副本。
答案 3 :(得分:1)
你可以使用if let或guard statement
private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
if let a = unloadedImagesRows[forLocation] as? [Int] {
//...success block
}
}
或使用保护声明
private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
guard let a = unloadedImagesRows[forLocation] else {
return
}
//...
}
了解更多信息。检查此link
答案 4 :(得分:1)
您可以按照以下方式进行检查。
private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
if let image = unloadedImagesRows[forLocation] {
//it is not nil
} else {
//it is nil
}
}
答案 5 :(得分:1)
var unloadedImagesRows = [String:[Int]]()
// if let
private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
if let _ = unloadedImagesRows[forLocation] {
} else {
unloadedImagesRows[forLocation] = [Int]()
}
unloadedImagesRows[forLocation]!.append(row)
}
// guard let
private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
guard let _ = unloadedImagesRows[forLocation] else {
unloadedImagesRows[forLocation] = [Int]()
return addToUnloadedImagesRow(row, forLocation: forLocation)
}
unloadedImagesRows[forLocation]!.append(row)
}
// nil coalescing
private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
var b = unloadedImagesRows[forLocation] ?? [Int]()
b.append(row)
unloadedImagesRows[forLocation] = b
}