Here's a simple function in Swift to determine if a number is prime:
main.swift291 chars20 lines
The function starts by checking if the number is less than or equal to 1. If so, it immediately returns false, since 1 and lower numbers are not prime. If the number is less than or equal to 3, it returns true, since 2 and 3 are prime.
The function then uses a while loop to check if the number is divisible by any integer from 2 up to the square root of the number. If it is, the function immediately returns false, since a prime number should only be divisible by 1 and itself.
If the function hasn't returned false after the loop, it returns true, since the number must be prime.
gistlibby LogSnag