How can Create Model class in swift and get values form model class in another class [closed]

假如想象 提交于 2019-12-09 23:32:08

问题


How can i create model class in Swift. I am getting errors wile accessing values form the model class. Thank you. Here I am attaching my demo project, U can download it


回答1:


This way you can add and get values from model class:

var user = User(firstName: "abcd", lastName: "efghi", bio: "biodata")
print("\n First name :\( user.firstName) \t Last  name :\( user.lastName) Bio :\( user.bio)")

OutPut will be:

 First name :abcd    Last  name :efghi Bio :biodata

EDIT

As per your requirement if you want to store object into your model class in AppDelegate then you have to create one global array of type User which will store your objects and when app loads you can append your object into that array with below code:

import UIKit
import CoreData

// Global array
var userData = [User]()

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        let user = User(firstName: "Silviu", lastName: "Pop", bio: "I f**ing ♡ Swift!!!")
        //Add object into userData
        userData.append(user)
        // Override point for customization after application launch.
        return true
    }

}

Now you can access your save object this way In your ViewController.swift class:

override func viewDidLoad() {
    super.viewDidLoad()
    let user = userData
    println(user[0].firstName)
    println(user[0].lastName)
    println(user[0].bio)

}

And your OutPut will be:

Silviu
Pop
I f**ing ♡ Swift!!!


来源:https://stackoverflow.com/questions/30914758/how-can-create-model-class-in-swift-and-get-values-form-model-class-in-another-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!