mercredi 24 juillet 2019

How do I unwrap an optional within a struct and use an if statement to print the optional?

I am getting an error message for my use of nil, and I am confused on how to properly unwrap the optional while placing it in an if statement to print if it is non-nil.

The following is my code:

struct DatingProfile{
  var Name: String
  var Age: Int
  var City: String
  var FavoriteMovie: String? 
  var Hobbies: String?   
}

  let myDatingProfile = DatingProfile(
    Name: "William",
    Age: 30,
    City: "North Hollywood",
    FavoriteMovie: nil,
    Hobbies: "Basketball"
  )

  if let myFavoriteMovie = FavoriteMovie = nil {
    print("\(Name) does not have a favorite movie")    
  } else {  
    print(myDatingProfile.FavoriteMovie)
  }      
}

The following is an error log:

exit status 1
main.swift:12:26: error: use of unresolved identifier 'FavoriteMovie'
if let myFavoriteMovie = FavoriteMovie = nil{
                         ^~~~~~~~~~~~~
main.swift:13:12: error: use of unresolved identifier 'Name'
  print("\(Name) does not have a favorite movie")
           ^~~~
main.swift:17:11: warning: expression implicitly coerced from 'String?' to 'Any'
    print(myDatingProfile.FavoriteMovie)
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.swift:17:27: note: provide a default value to avoid this warning
    print(myDatingProfile.FavoriteMovie)
          ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~
                                        ?? <#default value#>
main.swift:17:27: note: force-unwrap the value to avoid this warning
    print(myDatingProfile.FavoriteMovie)
          ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~
                                       !
main.swift:17:27: note: explicitly cast to 'Any' with 'as Any' to silence this warning
    print(myDatingProfile.FavoriteMovie)
          ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~
                                        as Any
main.swift:20:1: error: extraneous '}' at top level
}
^

Aucun commentaire:

Enregistrer un commentaire