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
Post a Comment