我正在编写一个带有命名元组的函数,并且必须返回该元组的超集。
例如,如果我要收到这样的命名元组:
// application function of AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
_ = coreDataStack.mainContext
guard let tabc = window?.rootViewController as? UITabBarController else {
fatalError("Tab bar controller mis-configured.")
}
// Set the status bar to white
guard let navc1 = tabc.viewControllers?[0] as? UINavigationController,
let wordLibVC = navc1.topViewController as? WordLibraryViewController else {
fatalError("Navigation controller[0] mis-configured.")
}
wordLibVC.coreDataStack = coreDataStack
wordLibVC.levelDict = levelDict
return true
}
// Core Data Stack Class
class CoreDataStack {
// MARK: - Properties
fileprivate let modelName: String
var storeDirectory: URL = NSPersistentContainer.defaultDirectoryURL()
lazy var mainContext: NSManagedObjectContext = {
return self.container.viewContext
}()
lazy var container: NSPersistentContainer = {
let container = NSPersistentContainer(name: self.modelName)
self.seedCoreDataContainerIfFirstLaunch()
container.loadPersistentStores { (storeDescription, error) in
if let error = error as? NSError {
fatalError("Could not load persistent stores. \(error), \(error.userInfo)")
}
}
return container
}()
init(modelName: String) {
self.modelName = modelName
}
}
// fetch function in ViewController
func executeRequest() {
let fetchRequest = NSFetchRequest<Word>(entityName: "Word")
fetchRequest.propertiesToFetch = ["level"]
let levelSort = NSSortDescriptor(key: "level", ascending: true)
fetchRequest.sortDescriptors = [levelSort]
do {
// The following line returns an empty array
let results = try coreDataStack.mainContext.fetch(fetchRequest)
// The above line returns an empty array
var levels: [Int] = []
for result in results {
levels.append(Int(result.level))
}
let distinctLevels = Set(levels)
let sortedLevels = Array(distinctLevels).sorted()
print(sortedLevels)
let stringLevels = sortedLevels.map{String($0)}
dataSource.append(stringLevels)
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
// This is the function that copies the store from the bundle to the directory
func seedCoreDataContainerIfFirstLaunch() {
let previouslyLaunched = UserDefaults.standard.bool(forKey: "previouslyLaunched")
if previouslyLaunched { return }
UserDefaults.standard.set(true, forKey: "previouslyLaunched")
// 1. sqlite file
let destSQLite = storeDirectory.appendingPathComponent("wordlib.sqlite")
let sourceSQLite = Bundle.main.url(forResource: "wordlib", withExtension: "sqlite")!
try? FileManager.default.removeItem(at: destSQLite)
do {
try FileManager.default.copyItem(at: sourceSQLite, to: destSQLite)
print("wordlib.sqlite seeded.")
} catch let error as NSError {
print("Could not copy sqlite file, \(error.localizedDescription)")
}
// 2. sqlite-shm file
let destSHM = storeDirectory.appendingPathComponent("wordlib.sqlite-shm")
let sourceSHM = Bundle.main.url(forResource: "wordlib", withExtension: "sqlite-shm")!
try? FileManager.default.removeItem(at: destSHM)
do {
try FileManager.default.copyItem(at: sourceSHM, to: destSHM)
print("wordlib.sqlite-shm seeded.")
} catch let error as NSError {
print("Could not copy shm file. \(error.localizedDescription)")
}
// 3. .sqlite-wal
let destWAL = storeDirectory.appendingPathComponent("wordlib.sqlite-wal")
let sourceWAL = Bundle.main.url(forResource: "wordlib", withExtension: "sqlite-wal")!
try? FileManager.default.removeItem(at: destWAL)
do {
try FileManager.default.copyItem(at: sourceWAL, to: destWAL)
print("wordlib.sqlite-wal seeded.")
} catch let error as NSError {
print("Error: \(error.localizedDescription), Could not copy wal file.")
}
}
我想返回一个看起来像这样的元组:
Person(name='Bob', age=30, gender='male')
目前我这样做:
Person(name='Bob', age=30, gender='male', x=0)
哪个好,但我不想像这样复制每个字段:
tuple_fields = other_tuple[0]._fields
tuple_fields = tuple_fields + ('x')
new_tuple = namedtuple('new_tuple', tuple_fields)
我希望能够遍历FIRST对象中的每个对象并复制它们。我的实际元组是30个字段。
答案 0 :(得分:8)
您可以尝试使用dict解包来缩短它,例如:
tuple = new_tuple(x=0, **other_tuple._asdict())