ios - 如何将结构追加到数组中? swift 4

标签 ios arrays iphone swift option-type

函数

import Foundation

struct Foods {
    var fid: Int
    var fname: String
    var hits: Int?
    var addr: String?
}

class Food {

    func getFoodsById(_ fid: Int) -> [Foods]? {
        var foods: Array<Foods>?
        let URL_GET_TEAMS:String = "http://jsm0803.iptime.org:81/html/sufoo/getFoodById.php"
        let requestURL = URL(string: URL_GET_TEAMS)

        let request = NSMutableURLRequest(url: requestURL!)

        request.httpMethod = "POST"
        //request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        let postParameters = "Fid=" + String(fid)
           // "name="+teamName!+"&member="+memberCount!;

        request.httpBody = postParameters.data(using: String.Encoding.utf8)


        let task = URLSession.shared.dataTask(with: request as URLRequest){data, response, error in

            if error != nil{
                print("error is \(error)")
                return;
            }
            let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) // 테스트용
            //print(dataString!)


            do{
                var itemJSON: Dictionary<String, Any>!
                itemJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? Dictionary


                let items:Array<Dictionary<String, Any>> = itemJSON["Food"] as! Array

                for i in 0 ..< items.count{
                    var food: Foods
                    let item = items[i]

                    let fid:Int = item["Fid"] as! Int
                    let fname: String = item["Fname"] as! String
                    let hits: Int? = item["Hits"] as? Int
                    let delegate_image:String? = item["Delegate_Image"]as? String

                    food = Foods(fid: fid, fname: fname, hits: hits, addr: delegate_image)

                    foods?.append(food)



                    print("fid ->", food.fid)
                    print("fname ->", food.fname)
                    if let f = food.hits {
                        print("hits ->", f)
                    }
                    else{
                        print("hits ->", food.hits as Any)
                    }
                    if let f = food.addr {
                        print("delegate_image -> ", f)
                    }
                    else {
                        print("delegate_image -> ", food.addr as Any)
                    }

                    print("==============")
                    print("")

                    print ("fid ==== ", foods?.first?.fid)
                    print ("fid ==== ", foods?.last?.fid)

                }
            }catch {
                print(error)
            }
        }
        task.resume()

        if let result = foods{
            for r in result{
                print ("r.fname")
                print (r.fname)
            }
        }
        print ("000000")
        return foods
    }

}

如果我在 Xcode 中运行这段代码,我会得到以下结果:

000000

fid -> 140

fname -> 밀 흑밀

hits -> nil

delegate_image -> ./pic_data/2309/20180423201954alj

==============

fid ==== nil
fid ==== nil

我想返回 [var foods: Array?] 值。 但是,尽管我为 Foods 结构创建了一些值并使用了 Array 的 append 函数以便将 Foods 值添加到 Array 中,但它没有用。 Array 中没有值,只有 nil。(fid ==== nil) 因此,返回该数组是没有用的。

我怎样才能得到正确的结果?

我需要获取如下值:

fid ==== 140
fid ==== 140

请帮我解决这个问题。 我想我错误地使用了 Optional。

最佳答案

主要问题是您没有启动您的食物数组。

//func getFoodsById(_ fid: Int) -> [Foods]? {
func getFoodsById(_ fid: Int) -> [Foods] {
    //var foods: Array<Foods>?
    var foods = [Foods]() // or  var foods: [Foods] = []

如果 ID 没有食物,您可以在这里启动数组并返回空列表作为结果。

并使用 FoodOperations 之类的名称将您的 Foods 结构重命名为 Food 和 Food 类。这会更有意义。

阅读this快速指南。

struct Food {
    ...
}
class FoodOperations {
    ...
}

if let error = error {
   print("error is \(error)")
   return;
}

print ("fid ==== ", foods.first?.fid ?? 0)

关于ios - 如何将结构追加到数组中? swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50098761/

相关文章:

ios - 多点连接减缓 View 创建

C# 在不使用 sort( ) 或 reverse( ) 的情况下反转字符串数组

iphone - iOS 帮助 : loaded the nib but the view outlet was not set

iPhone : In-App purchase query

iphone - 苹果商店允许的最大 Iphone 应用程序大小

iphone - 有没有办法获取在我的 UIWebView 中播放的视频的长度?我可以在某个位置开始我的电影吗?

ios - IB_DESIGNABLE,在预览中显示 View ?

iphone - 如何判断按下了哪个 MKPinAnnotation?

c - 如何使用带有标准输入流的 fscanf 终止 while 循环

Javascript - 使数组索引 toLowerCase() 不起作用