Swift滤波器实现

用Swift写的滤波器,代码如下:

   //Setting Start
   import UIKit
   func getTestValueUInt16()->UInt16{
       return UInt16(arc4random_uniform(255))
   }
   func getTestValueInt()->Int{
       return Int(arc4random_uniform(255))
   }
   //Setting End
    
   //Double Extension Start
   extension Double{//If you want to format you can use the extension.
       func format(f:String) -> String {
           return NSString(format: "%\(f)f",self) as String
       }
   }
   //Double Extension End
   //Extension Example Start
   //print(Double(3.1415).format(".2"))//There is the example to format Double
   //Extension Example End
    
   //Vayne-Lover Filter Start
   var qualityRecorder:[Int]=[255,255,255,255,255,255]
   func qualityUpdate<T>(inout num:[T]){
       for i in 0...(num.count-2){//The range is [0,count-2] because we use i+1
           num[i]=num[i+1]
       }
   }
   func qualityCalculate(num:[Int])->Double{
       let sum=num.reduce(0, combine:+)
       let maxNumber=num.reduce(0,combine: {max($0,$1)})//You should name different from max or min
       let minNumber=num.reduce(255, combine: {min($0, $1)})//The init value can't be zero
       return Double(sum-minNumber-maxNumber)/4.0
   //    let newNum=num.sort(<)
   //    var sumNumber=0
   //    for i in 1...(newNum.count-2) {//Another way
   //        sumNumber+=newNum[i]
   //    }
   //    return Double(sumNumber)/4.0
   }
   var qual:[Int]=[100,150,175,180]
   for i in 0...3{
       qualityUpdate(&qualityRecorder)
       qualityRecorder[5]=qual[i]
       print(qualityCalculate(qualityRecorder).format(".2"))
   }
   //Vayne-Lover Filter End

首先设置随机数的获取,模拟实验数据,接着对Double进行扩展,保证输出保留两位小数。

Easy Filter Settings

滤波器的核心思想为每次获取一个新的数去掉一个旧的数,然后进行求和,去掉最大最小值再求平均数。

Easy Filter Codes

接下来我准备多写一些滤波器,然后传到Github上。现在已经更新了4种滤波器。

获取代码的方法,安装git后在命令行输入:

   git clone https://github.com/Vayne-Lover/Swift-Filter.git