到目前為止,我正在使用type(of: )函式來找出變數的動態型別,并將其與Type.self檢查型別進行比較:
var x = 5
if(type(of: x) == Int.self)
{
print("\(x) is of type Int")
}
我做對了嗎?或者有沒有更好/首選的方法來檢查型別?
uj5u.com熱心網友回復:
我個人會使用
if(x is Int)
{
print("\(x) is of type Int")
}
如果您期望 x 是整數,而不是使用 typeof,因為它更具可讀性。但可以肯定的是,如果你愿意,你可以使用 typeOf 。兩者都同樣正確
uj5u.com熱心網友回復:
您可以使用;
if (x is Int) {
print("\(x) is of type Int")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/471646.html
