Avatar of aishenji

aishenji's solution

to Nth Prime in the Swift Track

Published at Mar 25 2020 · 0 comments
Test suite

Given a number n, determine what the nth prime is.

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

If your language provides methods in the standard library to deal with prime numbers, pretend they don't exist and implement them yourself.


Go through the project setup instructions for Xcode using Swift:


Notably from the source directory:

swift test runs tests
swift package generate-xcodeproj creates an Xcode project


A variation on Problem 7 at Project Euler http://projecteuler.net/problem=7

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.


import XCTest
@testable import NthPrimeTests



import XCTest
@testable import NthPrime

class NthPrimeTests: XCTestCase {
    func testFirst() {
        XCTAssertEqual(2, Prime.nth(1))

    func testSecond() {
        XCTAssertEqual(3, Prime.nth(2))

    func testSixthPrime() {
        XCTAssertEqual(13, Prime.nth(6))

    func testBigPrime() {
        XCTAssertEqual(104_743, Prime.nth(10_001))

    func testWeirdCase() {

    static var allTests: [(String, (NthPrimeTests) -> () throws -> Void)] {
        return [
            ("testFirst", testFirst),
            ("testSecond", testSecond),
            ("testSixthPrime", testSixthPrime),
            ("testBigPrime", testBigPrime),
            ("testWeirdCase", testWeirdCase),
//Solution goes in Sources
struct Prime {
    static var pri = [Int]()
    static var Ans:Int = 1
    static var k = 0
    static func nth(_ n:Int) -> Int? {
        if n <= 0 {
            return nil
        while k < n {
            Ans += 1
            var flag = true
            for i in pri {
                if Ans % i == 0 {
                    flag = false
            if flag {
                k += 1
        return pri[n-1]

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?