我想为Double
写一个扩展名,以便它可以给Int
赋值。
extension Double {
func toPercentage() -> Int {
var mutableSelf = self
var twoDigits = Double(round(1000*mutableSelf)/1000)
return Int(twoDigits) * 100
}
}
在线var twoDigits = Double(round(1000*mutableSelf)/1000)
编译器抛出红色-Cannot use mutating member on immutable value: 'self' is immutable
但是我确实将自己重新分配给mutableSelf
变量。 Double是一个结构,它不是引用类型,为什么会出现错误?
答案 0 :(得分:3)
由于扩展名为 db = get_db()
# Dumping to log to check if the db actually has the row
cur_e = db.execute('SELECT user_id, user_email FROM cld_user')
ie = cur_e.fetchall()
for i in ie:
print "ID: {} | Email: {}".format(i[0], i[1])
print "end of ID dump"
print user_email
# The above code does print out the row (even after hitting the back button)
try:
# This block however, fails when user submits the form after hitting the back button
print "Trying"
cur_ps = db.execute('SELECT user_id, user_uid FROM cld_user \
WHERE user_email = ?', [user_email])
user_id = cur_ps.fetchone()[0]
user_uid = cur_ps.fetchone()[1]
print "Row exists"
flash(user_id, "success")
except Exception:
print "Exception"
cur_p = db.execute('INSERT OR IGNORE INTO cld_user \
(user_uid, user_name, user_email, user_contact) \
VALUES (?, ?, ?, ?)', [user_uid, user_name,
user_email, user_contact])
user_id = cur_p.lastrowid
print "No row exists"
flash(user_id, "success")
,因此即使调用不匹配其签名,编译器也会将Double
推断为round()
的{{3}}方法。此行为已报告为错误:
mutating func round()
您可以使用引用全局C库函数
Double
或更妙的是,使用extension Double {
func toPercentage() -> Int {
let twoDigits = Darwin.round(1000*self)/1000
return Int(twoDigits * 100)
}
}
方法:
Double.rounded()
或者简单地
extension Double {
func toPercentage() -> Int {
let twoDigits = (1000*self).rounded()/1000
return Int(twoDigits * 100)
}
}
答案 1 :(得分:1)
extension Double {
func toPercentage() -> Int {
let twoDigits = Double((1000 * self / 1000).rounded())
return Int(twoDigits) * 100
}
}