我经常需要计算数值数组的均值和标准差.所以我为一些似乎有用的数字类型编写了一个小协议和扩展.如果我这样做有什么不妥,我只想反馈.具体来说,我想知道是否有更好的方法来检查类型是否可以转换为Double,以避免需要asDouble变量和init(_:Double)构造函数.
我知道允许算术的协议存在问题,但这似乎工作正常,使我无法将标准偏差函数放入需要它的类中.
protocol Numeric {
var asDouble: Double { get }
init(_: Double)
}
extension Int: Numeric {var asDouble: Double { get {return Double(self)}}}
extension Float: Numeric {var asDouble: Double { get {return Double(self)}}}
extension Double: Numeric {var asDouble: Double { get {return Double(self)}}}
extension CGFloat: Numeric {var asDouble: Double { get {return Double(self)}}}
extension Array where Element: Numeric {
var mean : Element { get { return Element(self.reduce(0, combine: {$0.asDouble + $1.asDouble}) / Double(self.count))}}
var sd : …Run Code Online (Sandbox Code Playgroud) 我正在使用SQLite库,其中查询返回可选值以及可能抛出错误.我想有条件地解包该值,或者如果它返回错误则收到nil.我不完全确定怎么说这个,这段代码会解释,这就是它的样子:
func getSomething() throws -> Value? {
//example function from library, returns optional or throws errors
}
func myFunctionToGetSpecificDate() -> Date? {
if let specificValue = db!.getSomething() {
let returnedValue = specificValue!
// it says I need to force unwrap specificValue,
// shouldn't it be unwrapped already?
let specificDate = Date.init(timeIntervalSinceReferenceDate: TimeInterval(returnedValue))
return time
} else {
return nil
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法避免不得不强行打开那里?在更新到Swift3之前,我没有被迫在这里强行打开包装.
以下是实际代码.只是想从所有条目中获取最新的时间戳:
func getLastDateWithData() -> Date? {
if let max = try? db!.scalar(eventTable.select(timestamp.max)){
let time = Date.init(timeIntervalSinceReferenceDate: TimeInterval(max!))
// …Run Code Online (Sandbox Code Playgroud)