Declaring custom types

Hi guys,


I have declared some custom types with the struct like this in Swift

struct tUser {

var userId: Int

var name: String

var birthday: tDate

var location: String

var province: String

var email: String

var userPassword: String

var picture: Image

var favorites: tFavorite

}


struct tDate {

var day: Int

var month: Int

var year: Int

}


struct tFavorite {

var identifyer: Int

}


The problem is that I want to initialize a varible with information in these types but I always have the error "Expressions are not allowed at the top level"


What I want to do is the following but the syntax is wrong


var newUser: tUser


newUser.userId = 0001

newUser.name = ...


Can someone help me to do this implementation? I can't do it by myself.


Thanks

Replies

You need to do the initi inside a func, for instance in viewDidLoad function.


You can simply declare:

     var newUser = tUser(userId: 1, name: "X")     // And all other properties

Or you could declare a computed var:

     var newUser: tUser = {
          let aUser = tUser(userId: 1, name: "", birthday…)     // All arguments
          return aUser
     }()


Note; struct names should begin with UpperCase


You write 0001, that will be just 1.

If you want to keep 0001 when displaying, you should either:

- save a String

- format the number when you display

String(format: "%04d", newUser.userId)


EDITED Note2

This is not only for strcut.

This is illegal at top level, but legal inside a func:

    var t: Int
    t = 0


But this is of course OK

    var t: Int = 0