2016-11-14 1 views
0
request(url!, method: .get, parameters: nil) 
     .responseJSON { response in 

      print(response.result) // result of response serialization 

      if let newJSON = response.result.value { 
       let json = JSON(newJSON) 
       for (key,subJson):(String, JSON) in json { 

        let age = subJson["age"] 
        let name = subJson["name"] 
        let status = subJson["status"] 

    //the code below looks kind of confusing if it gets longer 

        if age == "22"{ 
         if status == "highschool "{ 
          if name == "Leo"{ 
           //do something with the result 

JSON의 결과가 문자열과 동일한 지 확인하는 더 좋은 방법이 있습니까?정확한 JSON 비교 (SWIFT 3)

답변

1

이것은 pyramid of doom입니다. 그것을 제거하는 몇 가지 방법이 있으며 상황에 따라 적절한 것을 고를 필요가 있습니다. 기본적으로 방법은 다음과 같습니다.

  • 초기 리턴 및 guard 문 사용.
  • if-let 문을 하나로 결합하십시오.
  • for-where을 사용합니다.

이런 식으로 뭔가에 코드의 당신의 조각을 다시 작성할 수있는 모든 당신의 위 감안할 때 :

request(url!, method: .get, parameters: nil) 
    .responseJSON { response in 
     print(response.result) // result of response serialization 

     guard let newJSON = response.result.value else { return } 

     let json = JSON(newJSON) 

     for (key,subJson):(String, JSON) in json { 
      let age = subJson["age"] 
      let name = subJson["name"] 
      let status = subJson["status"] 

      if age == "22" && status == "highschool" && name == "Leo" { 
       //do something with the result 
      } 
     } 
    } 
+0

엑스 코드는'나에게 inser 요청 '이름 연령 상태'앞에 놓자. 그렇게하면 오류가 발생합니다. ** 조건부 바인딩을위한 이니셜 라이저는 옵션 타입을 가져야합니다 ** – leo0019

+0

@ leo0019'subJson [ "age"]'는 선택 사항이 아닙니다. 그렇다면이 가드 댄스를 할 필요가 없습니다. 그냥 정상적인 상수로 선언하십시오. 답변을 수정했습니다. – kovpas

1

두 대안 :

if age == "22" && status == "high school " && name == "Leo" { 

또는

switch (age, status, name) { 
    case ("22", "high school ", "Leo"): ... 
    ... 
    default: ... 
}