[英]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
可以是NSNumber
或NSNumber
的數組。
感謝不存在的文檔,我猜想,在 Swift 中,它將是Int
或Array<Int>
。
當我運行這段代碼時,我得到第二個if
to be true
。 所以,就我而言, family
是一個Array<Int>
。
這是我不明白的。 如果family
是Array<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.