swift Swift - 使用Struct进行Segue

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift Swift - 使用Struct进行Segue相关的知识,希望对你有一定的参考价值。

See:https://stackoverflow.com/questions/43823430/using-struct-to-pass-a-variable-swift

The right way to pass data would be to:

eliminate static variables;
give your struct a name that starts with uppercase letter;
create instance of your struct; and
pass this instance to the destination view controller in prepare(for:sender:).

01. In the first VC:

struct FbDemographics {
    var relationshipStatus: String?
    var gender: String?
    var userEducationHistory: String?
    var userLocation: String?
    var email: String?
    var name: String?
}

class ViewController: UIViewController {

    var demographics: FbDemographics?

    override func viewDidLoad() {
        super.viewDidLoad()

        performRequest()   // I actually don't think you should be initiating this in `viewDidLoad` ... perhaps in `viewDidAppear`
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? SecondViewController {
            destination.demographics = demographics
        }
    }

    func performRequest() {
        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, relationship_status, gender, user_location, user_education_history, email"]).start { connection, result, error in
            guard let userDataDict = result as? NSDictionary, error == nil else {
                print("\(error)")
                return
            }

            self.demographics = FbDemographics(
                relationshipStatus: userDataDict["relationship_status"] as? String,
                gender: userDataDict["gender"] as? String,
                userEducationHistory: userDataDict["user_education_history"] as? String,
                userLocation: userDataDict["user_location"] as? String,
                email: userDataDict["email"] as? String,
                name: userDataDict["name"] as? String
            )

            self.performSegue(withIdentifier: "LoginToHome", sender: self)
        }
    }

}

02. In the second (receiving) VC:

class SecondViewController: UIViewController {

    var demographics: FbDemographics!

    override func viewDidLoad() {
        super.viewDidLoad()

        let value = demographics.email  // this should work fine here
    }

}

以上是关于swift Swift - 使用Struct进行Segue的主要内容,如果未能解决你的问题,请参考以下文章

Swift之struct二进制大小分析

Swift之struct二进制大小分析

swift Swift,Struct和Inheritance:如何平衡使用Struct和Value Types的意愿以及继承的需要?

swift 在swift中收集单词的struct

Swift 使用 Struct 的 UnsafeMutablePointer 获取字符串错误的值

SWIFT:将字节从 NSData 粘贴到 Struct?