简体   繁体   中英

Swift Init Optional Array in Struct

I can do an element with optinal like below but I dont know how create optional Array in Struct.

struct HomeElement {
     var title:String!
     var description:String?
     var body:String!

     init(title:String!,description:String,body:String!) {
           self.title = title
           self.description = description
           self.body = body
      }
}

I get an exception below code that nil for UIImage Array. How can I do when the Images input comes as nil.

struct HomeElement {
     var title:String!
     var description:String?
     var body:String!
     var images = [UIImage]()

     init(title:String!,description:String,body:String!,images:[UIImage]) {
           self.title = title
           self.description = description
           self.body = body
           self.images = images
      }
}

You have to declare the variable as Optional.

struct HomeElement {
    var title:String!
    var description:String?
    var body:String!
    var images: [UIImage]?

    init(title:String!,description:String,body:String!,images:[UIImage]?) {
           self.title = title
           self.description = description
           self.body = body
           self.images = images
     }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM