ios - Can a Swift function accept only a range of values? -


what trying write generic function compresses image.

func compress(image: uiimage, withratio ratio: cgfloat) -> data? {     return uiimagejpegrepresentation(image, ratio) } 

but here compress()'s ratio can cgfloat value 0...∞, want accept 0.0...1.0. there way that?

as function can return nil, can check value of ratio before using it. if not in desired range, can return nil.

func compress(image: uiimage, withratio ratio: cgfloat) -> data? {     if 0...1 ~= ratio {         return uiimagejpegrepresentation(image, ratio)     } else {         return nil     } } 

or can throw exception:

enum compresserror: error {     case ratiooutofrange }  func compress(image: uiimage, withratio ratio: cgfloat) throws -> data? {     if 0...1 ~= ratio {         return uiimagejpegrepresentation(image, ratio)     } else {         throw compresserror.ratiooutofrange     } } 

Comments

Popular posts from this blog

sql - Time in datatime field -

javascript - How to split the success output from an Ajax post? -

java - sharing object across different classes -