我有一个核心数据框架来处理您可以使用coredata
做的所有事情,以使其与可编码协议更兼容。我剩下的只是更新数据了。我通过镜像作为参数发送的模型来存储和获取数据。因此,如果我只想更新我请求的模型中的1个特定值,则需要模型中的变量名。
public func updateObject(entityKey: Entities, primKey: String, newInformation: [String: Any]) {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityKey.rawValue)
do {
request.predicate = NSPredicate.init(format: "\(entityKey.getPrimaryKey())==%@", primKey)
let fetchedResult = try delegate.context.fetch(request)
print(fetchedResult)
guard let results = fetchedResult as? [NSManagedObject],
results.count > 0 else {
return
}
let key = newInformation.keys.first!
results[0].setValue(newInformation[key],
forKey: key)
try delegate.context.save()
} catch let error {
print(error.localizedDescription)
}
}
如您所见,newInformation
参数包含键和应该更新的值的新值。但是,我不想通过("first": "newValue")
我想通过spots.first : "newValue"
所以,如果我有这样的结构:
struct spots {
let first: String
let second: Int
}
我怎么只能从中获得1个名字?
我尝试过:
extension Int {
var name: String {
return String.init(describing: self)
let mirror = Mirror.init(reflecting: self)
return mirror.children.first!.label!
}
}
我想说些类似的话:
spots.first.name
但不知道如何
答案 0 :(得分:1)
不确定我是否理解问题,但是...这是什么?
services.AddSingleton<IFileProvider>(
new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/files")));
或者您可以尝试快速键路径:
class Spots: NSObject {
@objc dynamic var first: String = ""
@objc dynamic var second: Int = 0
}
let object = Spots()
let dictionary: [String: Any] = [
#keyPath(Spots.first): "qwerty",
#keyPath(Spots.second): 123,
]
dictionary.forEach { key, value in
object.setValue(value, forKeyPath: key)
}
print(object.first)
print(object.second)
但是,如果您要使用字典,则会遇到复杂(或不可能)的问题:
struct Spots {
var first: String = ""
var second: Int = 0
}
var spots = Spots()
let second = \Spots.second
let first = \Spots.first
spots[keyPath: first] = "qwerty"
spots[keyPath: second] = 123
print(spots)
您需要将let dictionary: [AnyKeyPath: Any] = [
first: "qwerty",
second: 123
]
投射回AnyKeyPath
,这似乎很复杂(如果可能的话)。
WritableKeyPath<Root, Value>