gpt4 book ai didi

swift - 使用 "for in"循环遍历结果以构建单独的数组

转载 作者:搜寻专家 更新时间:2023-11-01 06:40:11 25 4
gpt4 key购买 nike

SWIFT 核心数据我在设置 for - in 循环以从提取中收集结果时遇到问题。通过 fetch results[index] 获取单个结果没有问题,但是插入 for-in 循环给我一个错误(类型不匹配)或(类型不包含生成器中的成员)。我想使用获取结果来填充一个单独的数组。

非常感谢您提供的任何帮助。

代码摘录:

import Foundation
import UIKit
import CoreData
// globaals
var pickResult:String?
var pickMultiresult:[AnyObject]?
// add var
var fullnameMulti:[String]? // array of full names
var i:Int = 0
// end new var
class ClientPicker:UIViewController, UIPickerViewDelegate {
// connections

@IBOutlet weak var singleResult: UITextField!
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
@IBOutlet weak var firstname: UITextField!
@IBOutlet weak var status: UILabel!
var lastname:String = ""
var phone:String = ""
var email:String = ""

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
// MARK: ********** block 2 --- findClient ****
@IBAction func findClient(sender: AnyObject) {
let entityDescription = NSEntityDescription.entityForName("Contacts", inManagedObjectContext: managedObjectContext)
let request = NSFetchRequest()
request.entity = entityDescription
let pred = NSPredicate(format: "(firstname = %@)", firstname.text!)
request.predicate = pred

do {
var results = try managedObjectContext.executeFetchRequest(request)
multiresult = results
if results.count > 0 {
// let match = results[0] as! NSManagedObject NOTE: these return correct data for indices 0 and 3
// let match = results[3] as! NSManagedObject NOTE: these return correct data for indices 0 and 3
status.text = "There are \(results.count) people named \(firstname.text!)"
} else {
status.text = "No Match"
}
} catch let error as NSError {
status.text = error.localizedFailureReason
}



// for in loop to populate firstnameMulti array
i = 0
for i in results{
var p = i
let match = results[p] as! NSManagedObject

/* the following code returns correct fullname when used outside of for loop
but error when I use the for loop */
firstname.text = match.valueForKey("firstname") as? String
/***************** concatenate first and last names ********/
let first = match.valueForKey("firstname") as? String
let last = match.valueForKey("lastname") as? String
// concatenate
var fullname:String = ""
fullname = "\(first!) \(last!)"
singleResult.text = fullname
}
}

*/ error: value of type string has no member in Generator */

最佳答案

您正在循环中填充文本字段的文本,并在每次迭代时覆盖它。那没有任何意义。

要生成一个全名数组,获取你的对象并转换为正确的 NSManagedObject 子类,例如 Person 这样你就会得到一个 [Person] 数组,然后你可以简单地使用 map:

let nameList = results.map { "\($0.firstname) \($0.lastname)" }

关于swift - 使用 "for in"循环遍历结果以构建单独的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36485862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com