簡體   English   中英

嘗試處理可以是數組或數字的 object

[英]Trying do deal with an object that can be an array or a number

我正在嘗試從infoDictionary讀取UIDeviceFamily的值,如下所示:

if let family = Bundle.main.infoDictionary?["UIDeviceFamily"] {
  if family is Array<Int> {

  }
}

根據 2010 年的文檔, UIDeviceFamily可以是NSNumberNSNumber的數組。

感謝不存在的文檔,我猜想,在 Swift 中,它將是IntArray<Int>

當我運行這段代碼時,我得到第二個if to be true 所以,就我而言, family是一個Array<Int>

這是我不明白的。 如果familyArray<Int> ,則第二個if之后的下一行可能是

let firstValue = family.first

但這會失敗。

當它是數組或數字時,如何從family中提取值? 有沒有簡單的方法可以做到這一點?

嘗試

if let arr =  family as? Array<Int> {
   print(arr)
}
else if let item = family as? Int {
   print(item)
} 

另一種方法是使用帶有類型轉換模式的switch語句:

switch Bundle.main.infoDictionary?["UIDeviceFamily"] {
case let intArray as [Int]:
    print(intArray)
case let singleInt as Int:
    print(singleInt)
default:
    break // Something else, or `nil`.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM