How can Create Model class in swift and get values

2019-04-15 17:45发布

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条回答
做个烂人
2楼-- · 2019-04-15 18:07

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!!!
查看更多
登录 后发表回答