我正在尝试实现Dictionary扩展,我想处理可选值.但无论我做什么,如果我在[String: String?]字典上使用我的方法,它都无法选择性地绑定值.如何编写优雅处理可选值的字典的扩展?
考虑以下扩展:
extension Dictionary {
func someMethod() {
for (key, value) in self {
if let valueString = value as? String {
println(" \(key) = \(valueString)")
} else {
println(" \(key) = \(value) cannot be cast to `String`")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
请考虑以下代码:
let dictionary: [String: AnyObject?] = ["foo": "bar"]
dictionary.someMethod()
Run Code Online (Sandbox Code Playgroud)
它好奇地报道
foo = Optional(bar) cannot be cast to `String`
Run Code Online (Sandbox Code Playgroud)
我可以编写一个非扩展方法来处理带有可选值的字典参数,但是看不到如何将它作为扩展名来实现Dictionary.
我试图在Swift中构建一个数据结构,将Integer映射到一个对象数组(一个字典,其中int为键,数组为value).对象非常小,它们只需包装UIColor和Int.我有两个实现,一个使用Swift数组作为Dictionary的值类型,而另一个使用NSMutableArray作为值类型.我的Objective-C代码执行速度非常快,但我的Swift代码运行得非常慢.理想情况下,我不想使用NSMutableArray,并希望将其保留为Swift数组.原因是我正在编写算法和性能问题,我注意到了objC_msgSend的一些开销.任何人都可以帮我优化我的Swift代码吗?我做错了什么,或者这只是快速处理数组作为值类型的副产品?如果是,我想理解为什么值类型在这种情况下表现得如此之慢,我的选择是什么,以及这种情况如何能够在未来扩展?下面我发布了一个代码段和结果基准:
Swift数组代码:
let numColors = colorCount(filter: filter, colorInfoCount: colorInfo.count)
var colorCountsArray: [Int] = [Int]()
var countToColorMap: [Int:[CountedColor]] = [Int:[CountedColor]](minimumCapacity: capacity)
var topColors = [CountedColor]()
var startTime = CACurrentMediaTime()
for (color, colorCount) in colorInfo {
colorCountsArray.append(colorCount)
if countToColorMap[colorCount] != nil {
countToColorMap[colorCount]?.append(CountedColor(color: color, colorCount: colorCount))
} else {
countToColorMap[colorCount] = [CountedColor(color: color, colorCount: colorCount)]
}
}
var endTime = CACurrentMediaTime()
print("Time after mapping: \(endTime - startTime)")
Run Code Online (Sandbox Code Playgroud)
迅捷表现:
Time after mapping: 45.0881789259997
Run Code Online (Sandbox Code Playgroud)
NSMutableArray代码:
let numColors = colorCount(filter: filter, colorInfoCount: colorInfo.count)
var colorCountsArray: …Run Code Online (Sandbox Code Playgroud) 我正在深入研究Apples SpriteKit和GameplayKit示例代码,并发现了一个名为'DemoBots'的项目,用Swift编写.在项目中使用了一些非常有趣的概念,我想要适应我的项目.
我已经在将碰撞处理封装到一个处理程序类中,这与在该示例代码中处理碰撞的方式非常相似.
在这个项目中,我找到了一个名为的结构的代码RPColliderType:
struct RPColliderType: OptionSetType, Hashable, CustomDebugStringConvertible {
// MARK: Static properties
/// A dictionary to specify which `ColliderType`s should be notified of contacts with other `ColliderType`s.
static var requestedContactNotifications = [RPColliderType: [RPColliderType]]()
/// A dictionary of which `ColliderType`s should collide with other `ColliderType`s.
static var definedCollisions = [RPColliderType: [RPColliderType]]()
// MARK: Properties
let rawValue: UInt32
// MARK: Options
static var Obstacle: RPColliderType { return self.init(rawValue: 1 << 0) }
static var PlayerBot: RPColliderType { return …Run Code Online (Sandbox Code Playgroud) 意图:
通过Coinmarketcap API接收加密货币价格数据,将其解码为 SWIFT 中的自定义结构,并可能将该数据存储在数据库(CoreData 或 SQLite)中。
语境:
我收到以下错误JSONDecoder().decode:
Error serializing json: typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "status", intValue: nil), _DictionaryCodingKey(stringValue: "credit_count", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found a number instead.", underlyingError: nil))
Run Code Online (Sandbox Code Playgroud)
问题:
编码:
import UIKit
import PlaygroundSupport
// Defining structures
struct RootObject: Decodable {
let status: [String: StatusObject?]
let data: DataObject?
}
struct StatusObject: Decodable {
let credit_count: Int?
let elapsed: Int?
let error_code: Int?
let timestamp: String? …Run Code Online (Sandbox Code Playgroud) 我有一本字典<String,Loto>,Loto就像下面的对象;
Loto:
{
"success": true,
"data": {
"oid": "64kbbqi8dbxygb00",
"hafta": 961,
"buyukIkramiyeKazananIl": "",
"cekilisTarihi": "11/04/2015",
"cekilisTuru": "SAYISAL_LOTO",
"rakamlar": "03#02#48#16#15#08",
"rakamlarNumaraSirasi": "02 - 03 - 08 - 15 - 16 - 48",
"devretti": false,
"devirSayisi": 0,
"bilenKisiler": [
{
"oid": "64kbbxi8dbxyg403",
"kisiBasinaDusenIkramiye": 7.35,
"kisiSayisi": 185712,
"tur": "$3_BILEN"
},
{
"oid": "64kbbxi8dbxyg402",
"kisiBasinaDusenIkramiye": 53.05,
"kisiSayisi": 9146,
"tur": "$4_BILEN"
},
{
"oid": "64kbbxi8dbxyg401",
"kisiBasinaDusenIkramiye": 4532.2,
"kisiSayisi": 142,
"tur": "$5_BILEN"
},
{
"oid": "64kbbxi8dbxyg400",
"kisiBasinaDusenIkramiye": 1528438.75,
"kisiSayisi": 1,
"tur": "$6_BILEN"
}
], …Run Code Online (Sandbox Code Playgroud) 我从php重写了这段代码.我发现很难让它迅速发挥作用.
var arrayOfData = [AnyObject]()
for index in 1...5 {
var dict = [String: AnyObject]()
dict["data"] = [1,2,3]
dict["count"] = 0
arrayOfData.append(dict)
}
for d in arrayOfData {
let data = d as AnyObject
// I want to update the "count" value
// data["count"] = 8
print(data);
break;
}
Run Code Online (Sandbox Code Playgroud) 当我添加'AnyObject'类型的值时 通过以下方式输入类型'[String:AnyObject]'的字典,不能添加值,这实际上是我所期望的.在我看来,将可选类型分配给非可选类型应该会失败.
var myDict : [String : AnyObject] = [ "Key1" : "Value1" as AnyObject? ]
Run Code Online (Sandbox Code Playgroud)
但是,如果我首先初始化一个空字典,然后将值添加到它,为什么这个过程会起作用?
var myDict = [String : AnyObject]()
myDict["Key1"] = "Value1" as AnyObject?
Run Code Online (Sandbox Code Playgroud)
我在Apple的GenericKeychain示例中看到过这种方法 https://developer.apple.com/library/content/samplecode/GenericKeychain/Introduction/Intro.html
我如何纠正此代码以防止构建失败?基本上想要使用 ForEach 迭代基于 [ customEnum : customStrut ] 的字典。
否则,如果这是有问题的,是否有其他方法来实现 SwiftUI 支持?
错误
在“ForEach”上引用初始化程序“init(_:id:content:)”要求“[GCFilterViewOptions.FilterOptions : GCFilterViewOptions.FilterOptionValues]”符合“RandomAccessCollection”
类型 '(key: GCFilterViewOptions.FilterOptions, value: GCFilterViewOptions.FilterOptionValues)' 不能符合 'Hashable';只有 struct/enum/class 类型可以符合协议
代码
import SwiftUI
struct GCFilterViewOptions: View {
enum FilterOptions {
case NewLine
case Comma
case Space
}
struct FilterOptionValues {
var title : String
var selected : Bool
}
var filterSelections : [FilterOptions : FilterOptionValues] = [
FilterOptions.NewLine : FilterOptionValues(title: "New Line", selected: true),
FilterOptions.Comma : FilterOptionValues(title: "Comma", selected: true),
FilterOptions.Space : FilterOptionValues(title: "Space", selected: …Run Code Online (Sandbox Code Playgroud) 我试图将我的plist中的一些数据加载到数组中.在声明一个数组时,我做了类似的事情
var natureList : [Dictionary] = [] as! [Dictionary]
Run Code Online (Sandbox Code Playgroud)
那么我如何声明一个数组来从我的plist加载这些数据.?我知道它很简单,但这个小东西正在吃我的脑袋.任何帮助赞赏.
我试图在字典中找到条目的索引。我的字典如下:
// Dictionary
var questions: [[String:Any]] = [
[
"quesID": 1000,
"question": "What is the capital of Alabama?",
"answer": "Montgomery",
],
[
"quesID": 1001,
"question": "What is the capital of Alaska?",
"answer": "Juneau",
]
]
Run Code Online (Sandbox Code Playgroud)
我尝试使用indexOf,但是它不起作用。我的代码如下:
// Find index of dictionary entry with quesID of 1000
let indexOfA = questions.indexOf(1000) // Should return 0
// Find index of dictionary entry with quesID of 1001
let indexOfB = questions.indexOf(1001) // Should return 1
Run Code Online (Sandbox Code Playgroud) swift ×10
swift-dictionary ×10
arrays ×2
algorithm ×1
anyobject ×1
bit-masks ×1
gameplay-kit ×1
ios ×1
json ×1
optional ×1
sprite-kit ×1
swift3 ×1
swiftui ×1
value-type ×1