2017-06-23 64 views
0

我想檢查傳出變量的值是否爲0或1.我嘗試了下面的代碼來做同樣的事情,但我無法檢查它。在下面的代碼message是一個包含值爲XMPPMessageArchiving_Message_CoreDataObject的字典。如何檢查swift 3中的變量值?

如何檢查outgoing變量的值?

message詞典包含:

bareJid = "(...not nil..)"; 
bareJidStr = "[email protected]"; 
body = "{\"Date\":\"14 Jun 2017\",\"Time\":\"4:21PM\",\"body\":\"hello\",\"filePath\":\"\",\"isImportant\":\"N\",\"isMine\":true,\"msgid\":\"167-36\",\"receiver\":\"tester1\",\"sender\":\"tester3\",\"senderName\":\"tester3\"}"; 
composing = 0; 
message = "(...not nil..)"; 
messageStr = "<message xmlns=\"jabber:client\" to=\"[email protected]\" id=\"167-36\" type=\"chat\" from=\"[email protected]/Smack\"><body>{\"Date\":\"14 Jun 2017\",\"Time\":\"4:21PM\",\"body\":\"hello\",\"filePath\":\"\",\"isImportant\":\"N"; 
outgoing = 0; 
streamBareJidStr = "[email protected]"; 
thread = "2066797c-4f79-48f3-bd04-30658ee35e9f"; 
timestamp = "2017-06-14 11:20:41 +0000"; 

當調試outgoing變量的值隨後的Xcode示出它的類型是Any?和它的值是some

let outgoing = messasge.value(forKey: "outgoing") 
var isIncoming = true 

if let og = outgoing as? Int { 
    if og == 1 { 
     isIncoming = false 
    } 
} 
+0

嘗試讓傳出= messasge.value(forKey: 「離開」)作爲!詮釋,而不是讓出= messasge.value(forKey:「傳出」)。 – Tann

+0

我試過了,但它會引發運行時錯誤。 – samdroid

+0

當Xcode顯示任何類型的傳出?它的價值是一些。傳出是指針是否有意義? – samdroid

回答

2

如果您的字典值數據類型是Anyobject然後解開作爲NSNumber的,並轉換爲整數或布爾

if let outgoing = message["outgoing"] { 
     let convertedValue = Int(outgoing as! NSNumber) 
     if convertedValue == 1 { 
      isIncoming = false 
      print("Incoming false") 
     } 
    } 

實施例:

var messasge = [String: AnyObject]() 
     messasge["outgoing"] = "1" as AnyObject; 

     if let outgoing = messasge["outgoing"] { 
      let convertedValue = Int(outgoing as! NSNumber) 
      if convertedValue == 1 { 
       print("Incoming false") 
      } 
     } 

消息[ 「離開」]值數據類型爲String

var messasge = [String: Any]() 

    messasge["outgoing"] = "1" ; 

if let outgoing = messasge["outgoing"] as? String, outgoing == "1" { 
    isIncoming = false 
    } 

消息[ 「離開」]值數據類型是Int

var messasge = [String: Any]() 

messasge["outgoing"] = 1 ; 

if let outgoing = messasge["outgoing"] as? Int, outgoing == 1 { 
    isIncoming = false 
    } 
+0

這是如何解決問題中的問題? – rmaddy

+0

很抱歉更新了我的答案 – Subramanian

0
let outgoing : String = messasge.value(forKey: "outgoing") 
let og = Int(outgoing) 
if og == 1 
{// isIncoming = false 
} 
else 
{ 
    //isIncoming = true 
}