Swift Utilities


CGRectMake2

func CGRectMake2(point:CGPoint,_ size:CGSize)->CGRect{
    return CGRectMake(point.x,point.y,size.width,size.height)
}

UIViewの相対座標系

public extension UIView{
    func relativeWidthGetterBasedOnRatio(ratio:CGFloat)->CGFloat->CGFloat{
        return { self.bounds.size.width * $0 / ratio }
    }

    func relativeHeightGetterBasedOnRatio(ratio:CGFloat)->CGFloat->CGFloat{
        return { self.bounds.size.height * $0 / ratio }
    }

    func relativePointGetterBasedOnRatio(ratio:CGSize)->(x:CGFloat->CGFloat,y:CGFloat->CGFloat){
        return (relativeWidthGetterBasedOnRatio(ratio.width),relativeHeightGetterBasedOnRatio(ratio.height))
    }
}

    //サイズ1:1.168のUIViewのメンバメソッド内で   
    backgroundColor = UIColor.greenColor()
    let relsize = CGSizeMake(1,1.618)
    let rel = relativePointGetterBasedOnRatio(relsize)
    let point = CGPointMake(0, rel.y(0.618))
    let size = CGSizeMake(rel.x(1.0),rel.y(1.0))
    let frame = CGRectMake2(point,size)
    let fixedframe = CGRectInset(frame, rel.x(0.1), rel.y(0.1))
    let view = UIView(frame: fixedframe)
    view.backgroundColor = UIColor.blueColor()
    addSubview(view)    

1~nのランダムな重複なし数列生成

func shuffledIntegers(size:Int)->[Int]{
    var tmp = [Int](0 ..< size)
    for i in 0..<size{
        let c = arc4random_uniform_Int(size-i)
        if c != n-i-1 {
            swap(&tmp[c], &tmp[n-i-1])
        }
    }
    return tmp
}

func arc4random_uniform_Int(a:Int)->Int{
    return Int(arc4random_uniform(UInt32(a)))
}