我有創造出有4個數據成員訪問時,它不應該是零類測試模型(指返回默認值)可選值的方式
extension Double {
/// Rounds the double to decimal places value
func roundTo(places:Int = 2) -> Double
{
let divisor = pow(10.00, Double(places))
return (self * divisor).rounded()/divisor
}
}
class TestingModel{
var id : String!
var name : String! = "abc" /*It is not working*/
var price : Double! = 0.00
var uniqueId : Int! = 1
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(dictionary: [String:Any])
{
id = (dictionary["id"] as? String) ?? "" //I dont want to do like this way
name = dictionary["name"] as? String
price = (dictionary["price"] as? Double)?.roundTo() ?? 0.00
uniqueId = dictionary["unique_id"] as? Int
}
}
let t:TestingModel = TestingModel.init(dictionary: ["x id" : "x012y12345z45","x name":"test1","x price":100.0,"uniqueId":1236.0])
let testString = "Jd " + t.id
print(testString) //Perfect
print(t.name)
print(t.price) /* Only one decemal point is printed */
獲得輸出
Jd
nil
0.0
預計產量
Jd
ABC/應該返回的ABC,而不是零/
0.00/兩個小數點complulsury/
我在
實際上是說,如果我給你零值變量,然後它應該保持它的默認值而不用寫這個可選的鏈接?? 「abc」 in構造函數
如果您的'dictionary'可以返回零,那麼您必須手動將其更改爲設置任何默認值,如問題所示。沒有出路。 – adev
okey我想我必須刪除這個問題,因爲沒有辦法來優化以上問題 –
所以你們應該刪除你的答案以及 –