Skip to content

Tag: Swift

RawRepresentable and associated values

RawRepresentable is a protocol in Swift standard library and enables converting from a custom type to raw value type and back. In this post we’ll be looking into how to implement RawRepresentable for enumeration containing an associated value. Conforming to RawRepresentable Implementing RawRepresentable requires three steps: firstly, choose RawValue type; secondly, implement initialiser where RawValue type is matched to one of the cases in the enumeration, and thirdly, rawValue getter where enumeration cases are converted into RawValue type. In the example we’ll be looking into enumeration representing scenes: home, levelSelection… Read more RawRepresentable and associated values

Random float and integer in Swift

Getting a random number within a range is a very common operation. There are multiple ways of extending Swift language to add support for getting random values within a specified range. After experimenting with different implementations like utility functions, integer and float extensions I have found that the most natural way of doing it is to extend ClosedRange. This will allow to write a very readable code: Random floating point values 1. Get a random value using a max possible range (note that arc4random_uniform excludes the upper bound). 2. Convert… Read more Random float and integer in Swift

Clamping numbers in Swift

Clamping a value is an operation of moving the value to a range of allowed values. It can be achieved by comparing the value with allowed minimum and maximum values. For example I was deforming SKWarpGeometryGrid from the direction of a point outside the grid and needed to constrain angles between grid points and the contact point. Maximum and minimum allowed angles were related to the angle between the contact point and the grid’s center point. The solution I propose extends FloatingPoint and BinaryInteger protocols and gives a very readable… Read more Clamping numbers in Swift