-1

this is my code:

 func uplouadPost() {

    // shortcut to data to be php

   let parseJSON = UserDefaults.standard.value(forKey: "parseJSON") as? 
   NSDictionary
   let userID = parseJSON!["userID"] as! String

....

  if error == nil {

            do {

                // json containes $returnArray from php
                let json = try JSONSerialization.jsonObject(with: data!, 
  options: .mutableContainers) as? NSDictionary

                print("========================\(userID)")      

print I get ========================Optional(23)

But I don't want Optioanl

how to just get 23

What's more, I tried to unwrap the "userID" by this way. However it doesn't work

let unwrappedUserID = [userID]

print (unwrappedUserID)

Thank you guys

Sulthan
  • 128,090
  • 22
  • 218
  • 270
Ding
  • 11
  • 1
  • 3

2 Answers2

0

The best method of checking for and unwrapping Optionals is using either a guard statement or if-let statements.

So suppose you have a dictionary defined as:

let parseJson: [String: Any]? = ["userId": 23]

Even though it has a value, it is still an Optional type so to access the values in the dictionary we want, we need to check for the possibility of it having a nil value, assuming we didn't create it and know that it has a real value.

Using if-let statements, we can do:

if let json = parseJson {
  // WILL ONLY EXECUTE IF parseJson IS NOT nil
  // json is now of type [String: Any] instead of [String: Any]?
  let userId = json["userId"]
  print("=========\(userId)") // =========23
}

This creates a new scope where the json constant now contains the non-nil and unwrapped optional value of parseJson. In that case if parseJson did equal nil, then the code inside of the if-let block would not execute.

The other option is a guard statement, which is very similar.

guard let json = parseJson else {
  // ONLY EXECUTES IF parseJson IS nil
  // MUST EXIT CURRENT SCOPE AS A RESULT
  return // or throw NSError()
}

let userId = json["userId"]
print("==========\(userId)") // ==========23

In this case, the code after the guard will only execute if parseJson is non-nil because the inside of the guard block must exit the scope.

m_callens
  • 6,100
  • 8
  • 32
  • 54
-2

Try this, let unwrappedUserID = userID!

f_qi
  • 689
  • 8
  • 21
  • 2
    It is bad practice to implicitly unwrap optionals without having done `nil` value or error checking – m_callens Apr 20 '17 at 17:59
  • true. I'm only showing OP the format of unwrapping optional. `nil` and error checking is on his coding practice. – f_qi Apr 20 '17 at 18:12