Swift - 通过块传递struct数组并检索成员

时间:2017-01-02 22:52:41

标签: ios arrays swift

我有一个完成块,它将结构数组数组交给另一个viewcontroller。

此数据在viewDidLoad中收到,如:

  var packArray = [Any]()// the block is returning Any

    override func viewDidLoad() {
        super.viewDidLoad()
             BuildArray.buildArrayFromQuery(queryForCollection: "Pack", sender: self) { (result) in     
                  self.packArray = [result]
             }
    }

打印这个self.packArray在一行中返回以下内容,我现在不知道如何提取数据。

[[static ParseStarterProject_Swift.BuildArray.(buildArrayFromQuery (queryForCollection : Swift.String, sender : __ObjC.UIViewController, completeBlock : (Any) -> ()) -> ()).(collectionStruct #1)(name: "pk00", description: "This is some text", title: "Not a murderer", image: <PFFile: 0x60000005fc80>, id: "rHITAAHJYk"), static ParseStarterProject_Swift.BuildArray.(buildArrayFromQuery (queryForCollection : Swift.String, sender : __ObjC.UIViewController, completeBlock : (Any) -> ()) -> ()).(collectionStruct #1)(name: "pk01", description: "This is some text", title: "Addiction", image: <PFFile: 0x600000240300>, id: "uGHHpPF89e"), static ParseStarterProject_Swift.BuildArray.(buildArrayFromQuery (queryForCollection : Swift.String, sender : __ObjC.UIViewController, completeBlock : (Any) -> ()) -> ()).(collectionStruct #1)(name: "pk02", description: "This is some text", title: "Towels are noisy", image: <PFFile: 0x600000240570>, id: "PeM7hJ4sih"), static ParseStarterProject_Swift.BuildArray.(buildArrayFromQuery (queryForCollection : Swift.String, sender : __ObjC.UIViewController, completeBlock : (Any) -> ()) -> ()).(collectionStruct #1)(name: "pk03", description: "This is some text", title: "Class action", image: <PFFile: 0x6000002407e0>, id: "LoSXT2PFoS"), static ParseStarterProject_Swift.BuildArray.(buildArrayFromQuery (queryForCollection : Swift.String, sender : __ObjC.UIViewController, completeBlock : (Any) -> ()) -> ()).(collectionStruct #1)(name: "pk04", description: "This is some text", title: "Beer", image: <PFFile: 0x600000240a50>, id: "vxEsd13twt"), static ParseStarterProject_Swift.BuildArray.(buildArrayFromQuery (queryForCollection : Swift.String, sender : __ObjC.UIViewController, completeBlock : (Any) -> ()) -> ()).(collectionStruct #1)(name: "pk05", description: "This is some text", title: "Not again...", image: <PFFile: 0x600000240cc0>, id: "JNqaAgtdRb"), static ParseStarterProject_Swift.BuildArray.(buildArrayFromQuery (queryForCollection : Swift.String, sender : __ObjC.UIViewController, completeBlock : (Any) -> ()) -> ()).(collectionStruct #1)(name: "pk06", description: "This is some text", title: "Foreign cars", image: <PFFile: 0x600000240f30>, id: "Hb16TDXGbz"), static ParseStarterProject_Swift.BuildArray.(buildArrayFromQuery (queryForCollection : Swift.String, sender : __ObjC.UIViewController, completeBlock : (Any) -> ()) -> ()).(collectionStruct #1)(name: "pk07", description: "This is some text", title: "Skin problems", image: <PFFile: 0x6000002411a0>, id: "MUYDMnJCrU"), static ParseStarterProject_Swift.BuildArray.(buildArrayFromQuery (queryForCollection : Swift.String, sender : __ObjC.UIViewController, completeBlock : (Any) -> ()) -> ()).(collectionStruct #1)(name: "pk08", description: "This is some text", title: "Junk food", image: <PFFile: 0x600000241410>, id: "yowAfJlcmr"), static ParseStarterProject_Swift.BuildArray.(buildArrayFromQuery (queryForCollection : Swift.String, sender : __ObjC.UIViewController, completeBlock : (Any) -> ()) -> ()).(collectionStruct #1)(name: "pk09", description: "This is some text", title: "Delusion", image: <PFFile: 0x600000241680>, id: "TiLAKBPmaD")]]

以前我用过:

cell.labelCell.text = self.packArray[indexPath.item].packDescription

但现在返回没有成员packDescription。我可能会去使用字符串处理并创建一个混乱,但必须有一个更好的方法将数据作为一个实际的数组。我知道我将其转换为Any,但无法找到另一种方法从结构数组中通过完成块获取数据。

-----编辑----

在创建数组的类中,有一个struct和来自struct的数组 结果通过completeBlock传递为Any

class func buildArrayFromQuery(queryForCollection: String,
       sender: UIViewController, 
       completeBlock: @escaping (_ result: Any) -> Void) {

    struct collectionStruct {
        var name : String
        var description : String
        var title : String
        var image : PFFile
        var id: String
    }

        var collectionArray = [collectionStruct]()

然后从PFQuery创建,结果数组将传回完成处理程序

query.findObjectsInBackground(block: { (objects, error) in

if error != nil {
    print(error!)

} else if let packs = objects {


    for object in packs {

        print(fromName)

        print(object)

        let arrayName = object.object(forKey: fromName) as! String
        let arrayDescription = object.object(forKey: fromDescription) as! String
        let arrayTitle = object.object(forKey: fromTitle) as! String
        let arrayImage = object.object(forKey: fromImage) as! PFFile
        let arrayID = object.objectId as String!

        collectionArray.append(collectionStruct(name: arrayName, description: arrayDescription, title: arrayTitle, image: arrayImage, id: arrayID!))
    }

}


completeBlock(result: collectionArray)

})

2 个答案:

答案 0 :(得分:1)

您需要将查询结果强制转换为所需类型。如果使packArray成为可选项,则可以使用

直接指定它
var packArray: [collectionStruct]?

self.packArray = result as? [collectionStruct]

使用该代码,如果结果无法转换为正确的数组类型,则self.packArray将包含nil。

或者您可以使用可选绑定:

var packArray: [collectionStruct] = []

...

if structsArray = result as [collectionStruct] {
  self.packArray = structsArray
}

您应该在viewDidLoad之外定义packArray:

var packArray: [collectionStruct] = []

override func viewDidLoad() {
  super.viewDidLoad()
    BuildArray.buildArrayFromQuery(queryForCollection: "Pack", 
     sender: self) { 
      (result) in 
      if structsArray = result as [collectionStruct] {
        self.packArray = structsArray
     }
}

您的代码在viewDidLoad中定义了一个局部变量packArray,这会让事情变得混乱。我建议不要使用实例变量和具有相同名称的局部变量。

答案 1 :(得分:0)

非常感谢Duncan C的投入,感谢你的回答是正确的我只想分享我如何调整它以使其正常工作。

在类外定义了struct,这让我在完成处理程序中使用[collectionStruct]。

var method = function () {
    return new Promise(function(resolve) {
        var output = [];
        var lineReader = require('readline').createInterface({
          input: require('fs').createReadStream('file.csv')
        });

        lineReader.on('line', function (line) {
            var jsonFromLine = {};
            var lineSplit = line.split(',');
            // select columns you want
            jsonFromLine.req = lineSplit[0];
            jsonFromLine.column1 = lineSplit[1];
            // ...  
            if (jsonFromLine.req === 'RQ0191223') {
                output.push(jsonFromLine);
            }
        });

        lineReader.on('close', function (line) {
            resolve(output);
        }); 
    });
}


method().then(function(outputOfResolve) { console.log(outputOfResolve); });

然后在查询后返回数组

struct collectionStruct {
    var name : String
    var description : String
    var title : String
    var image : PFFile
    var id: String
}

class BuildArray: UICollectionViewController {

    class func buildArrayFromQuery(queryForCollection: String, 
                  sender: UIViewController, 
                    completeBlock: @escaping (_ result: [collectionStruct]) -> Void) {

然后在Duncan C建议的其他课程中

completeBlock(collectionArray)

这仍然会发出警告:

if let structsArray = result as? [collectionStruct] {
     self.packArray = structsArray
}

很难看到我能在这做什么。