Search code examples
swiftinitializer

swift initializer optional and non-optional at the same time?


https://github.com/Hearst-DD/ObjectMapper requires me to have

 required init?(_ map: Map){
 }

I'd like to instantiate Foo() but it is Foo? type not Foo.

I added the following initializer but no avail.

 override init() {
 }

Solution

  • ** edit ** Sorry for the false call..

    I had problem with the below code.

     var foo = Mapper<Foo>().map(jsonString)
     if foo != nil {
         return foo!
     }
    
     foo = Foo()
     return foo
    

    I think the problem is when i declared var foo it's declared as Foo? type and foo = Foo() is still Foo?

    so I changed the code to

     var foo = Mapper<Foo>().map(jsonString)
     if foo != nil {
         return foo!
     }
    
     return Foo()
    

    and it seems working.