用 Swift 語言輸入型別
型別轉換
型別轉換是一種檢查例項型別的方法,或者將該例項視為與其自己的類層次結構中的其他位置不同的超類或子類。
Swift 中的型別轉換是使用 is 和 as 運算子實現的。這兩個運算子提供了一種簡單而富有表現力的方法來檢查值的型別或將值轉換為其他型別。
溯造型
某個類型別的常量或變數實際上可能是指幕後子類的例項。在你認為是這種情況的情況下,你可以嘗試使用型別轉換運算子(as?或!)向下轉換為子類型別。
由於向下轉換可能會失敗,因此型別轉換運算子有兩種不同的形式。條件形式,作為?,返回你嘗試向下轉換的型別的可選值。強制形式,作為!,嘗試向下轉換並強制 - 將結果展開為單個複合動作。
當你不確定向下轉換是否成功時,請使用型別轉換運算子的條件形式(作為?)。這種形式的運算子將始終返回一個可選值,如果無法進行向下轉換,則該值將為 nil。這使你可以檢查成功的向下轉發。
僅當你確定向下轉換將始終成功時,才使用型別轉換運算子的強制形式(作為!)。如果你嘗試向下轉換為不正確的類型別,則此形式的運算子將觸發執行時錯誤。瞭解更多。
字串到 Int&Float 轉換: -
let numbers = "888.00"
let intValue = NSString(string: numbers).integerValue
print(intValue) // Output - 888
let numbers = "888.00"
let floatValue = NSString(string: numbers).floatValue
print(floatValue) // Output : 888.0
浮點到字串轉換
let numbers = 888.00
let floatValue = String(numbers)
print(floatValue) // Output : 888.0
// Get Float value at particular decimal point
let numbers = 888.00
let floatValue = String(format: "%.2f", numbers) // Here %.2f will give 2 numbers after decimal points we can use as per our need
print(floatValue) // Output : "888.00"
整數到字串值
let numbers = 888
let intValue = String(numbers)
print(intValue) // Output : "888"
浮點到字串值
let numbers = 888.00
let floatValue = String(numbers)
print(floatValue)
String 的可選浮點值
let numbers: Any = 888.00
let floatValue = String(describing: numbers)
print(floatValue) // Output : 888.0
可選 String 到 Int 值
let hitCount = "100"
let data :AnyObject = hitCount
let score = Int(data as? String ?? "") ?? 0
print(score)
從 JSON 向下轉換值
let json = ["name" : "john", "subjects": ["Maths", "Science", "English", "C Language"]] as [String : Any]
let name = json["name"] as? String ?? ""
print(name) // Output : john
let subjects = json["subjects"] as? [String] ?? []
print(subjects) // Output : ["Maths", "Science", "English", "C Language"]
從 Optional JSON 轉發值
let response: Any = ["name" : "john", "subjects": ["Maths", "Science", "English", "C Language"]]
let json = response as? [String: Any] ?? [:]
let name = json["name"] as? String ?? ""
print(name) // Output : john
let subjects = json["subjects"] as? [String] ?? []
print(subjects) // Output : ["Maths", "Science", "English", "C Language"]
根據條件管理 JSON 響應
let response: Any = ["name" : "john", "subjects": ["Maths", "Science", "English", "C Language"]] //Optional Response
guard let json = response as? [String: Any] else {
// Handle here nil value
print("Empty Dictionary")
// Do something here
return
}
let name = json["name"] as? String ?? ""
print(name) // Output : john
let subjects = json["subjects"] as? [String] ?? []
print(subjects) // Output : ["Maths", "Science", "English", "C Language"]
用條件管理無響應
let response: Any? = nil
guard let json = response as? [String: Any] else {
// Handle here nil value
print("Empty Dictionary")
// Do something here
return
}
let name = json["name"] as? String ?? ""
print(name)
let subjects = json["subjects"] as? [String] ?? []
print(subjects)