![](/img/trans.png)
[英]In Swift 4, how can you get the string-representation of a data type stored in a variable of type 'Any'?
[英]How can I access values stored in a variable of type “Any”
我可以很容易地將值存儲在Any
類型的變量中,但是我不知道如何訪問它。
只是簡單的嘗試指派a
給i
給我這個錯誤信息: error: cannot convert value of type 'Any' to specified type 'Int'
並嘗試將其error: protocol type 'Any' cannot conform to 'BinaryInteger' because only concrete types can conform to protocols
給我以下錯誤消息: error: protocol type 'Any' cannot conform to 'BinaryInteger' because only concrete types can conform to protocols
let a: Any = 1
//this doesn't work
let i: Int = a
//this doesn't work
let i: Int = Int(a)
它不起作用,因為Int沒有接受類型為Any的初始化程序。 為了使其工作,您需要告訴編譯器a實際上是一個Int。 您可以這樣操作:
let a: Any = 1
let i: Int = a as! Int
編輯:如果不確定a的類型,則應使用可選的強制轉換。 有很多方法。
let i1: Int? = a as? Int // have Int? type
let i2: Int = a as? Int ?? 0 // if a is not Int, i2 will be defaulted to 0
guard let i3 = a as? Int else {
// what happens otherwise
}
您可以訪問它。 只是a
。
但除此之外,您無能為力。 除了少數實際通用的功能( print
, dump
等)之外,使用Any
確實可以做很多事情。
普遍性和有用性之間存在梯度。 一個極端是Any
。 這幾乎沒有用。 它不需要任何符合標准的類型。 但是結果是,它是如此的普遍。 從字面上看,所有類型都符合它。
另一個極端是像Int
這樣的具體類型。 如果您有一個期望為Int
的參數,則僅允許使用一種類型的值: Int
。 但是這種特殊性會為您帶來實用性。 您知道此值支持加,乘,轉換為字符串等。
對Any
執行任何有用的唯一方法是使用as
/ as?
向下轉換它as?
/ as!
變成更具限制性(較不通用)的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.