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

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -