<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&family=DM+Mono:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&display=swap" rel="stylesheet"/>

10 More Pattern Programs in Swift — Spiral, Diamond & More

By Mihir Pipermitwala · 6 min read

⚡ TL;DR

10 intermediate pattern programs in Swift — spiral matrix, hollow diamond, letter triangle, Fibonacci triangle, plus sign, and more. Code and output.

A follow-up to our creative Dart patterns and Go patterns posts, here are 10 pattern programs in Swift. Each one builds interview muscle while staying readable.


1. Spiral Matrix

Fill an n x n matrix with numbers in spiral order.

Copy
1  2  3  4
12 13 14 5
11 16 15 6
10 9  8  7
Copy
import Foundation

func spiralMatrix(_ n: Int) {
    var m = Array(repeating: Array(repeating: 0, count: n), count: n)
    var num = 1
    var top = 0, bottom = n - 1, left = 0, right = n - 1

    while top <= bottom && left <= right {
        for i in left...right { m[top][i] = num; num += 1 }
        top += 1
        for i in top...bottom { m[i][right] = num; num += 1 }
        right -= 1
        for i in stride(from: right, through: left, by: -1) { m[bottom][i] = num; num += 1 }
        bottom -= 1
        for i in stride(from: bottom, through: top, by: -1) { m[i][left] = num; num += 1 }
        left += 1
    }

    for row in m {
        print(row.map { String(format: "%2d", $0) }.joined(separator: " "))
    }
}

spiralMatrix(4)

Output

Copy
 1  2  3  4
12 13 14  5
11 16 15  6
10  9  8  7

2. Hollow Diamond

Diamond outline, hollow inside.

Copy
  *
 * *
*   *
 * *
  *
Copy
func hollowDiamond(_ n: Int) {
    func row(_ i: Int) {
        let prefix = String(repeating: " ", count: n - i)
        let core: String
        if i == 1 {
            core = "*"
        } else {
            core = "*" + String(repeating: " ", count: 2 * i - 3) + "*"
        }
        print(prefix + core)
    }

    for i in 1...n { row(i) }
    for i in stride(from: n - 1, through: 1, by: -1) { row(i) }
}

hollowDiamond(3)

Output

Copy
  *
 * *
*   *
 * *
  *

3. Letter Triangle

Each row adds one more letter from A.

Copy
A
A B
A B C
A B C D
A B C D E
Copy
func letterTriangle(_ n: Int) {
    for i in 0..<n {
        let row = (0...i).map { String(UnicodeScalar(65 + $0)!) }
        print(row.joined(separator: " "))
    }
}

letterTriangle(5)

Output

Copy
A
A B
A B C
A B C D
A B C D E

4. Number Stair

Row i contains i copies of i.

Copy
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Copy
func numberStair(_ n: Int) {
    for i in 1...n {
        print(Array(repeating: i, count: i).map(String.init).joined(separator: " "))
    }
}

numberStair(5)

Output

Copy
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

5. Fibonacci Triangle

Fibonacci numbers continue across rows.

Copy
0
1 1
2 3 5
8 13 21 34
55 89 144 233 377
Copy
func fibonacciTriangle(_ n: Int) {
    var a = 0, b = 1
    for i in 1...n {
        var row: [String] = []
        for _ in 0..<i {
            row.append("\(a)")
            let next = a + b
            a = b
            b = next
        }
        print(row.joined(separator: " "))
    }
}

fibonacciTriangle(5)

Output

Copy
0
1 1
2 3 5
8 13 21 34
55 89 144 233 377

6. Binary Triangle

Alternating 1s and 0s, starting with 1.

Copy
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
Copy
func binaryTriangle(_ n: Int) {
    for i in 1...n {
        let row = (1...i).map { (1 + i + $0) % 2 }
        print(row.map(String.init).joined(separator: " "))
    }
}

binaryTriangle(5)

Output

Copy
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1

7. Plus Sign

A + made of stars.

Copy
  *
  *
*****
  *
  *
Copy
func plusSign(_ n: Int) {
    let mid = n / 2
    for i in 0..<n {
        var line = ""
        for j in 0..<n {
            line += (i == mid || j == mid) ? "*" : " "
        }
        print(line)
    }
}

plusSign(5)

Output

Copy
  *
  *
*****
  *
  *

8. Hollow Pyramid

Pyramid with hollow inside.

Copy
    *
   * *
  *   *
 *     *
*********
Copy
func hollowPyramid(_ n: Int) {
    for i in 1...n {
        var line = String(repeating: " ", count: n - i)
        if i == n {
            line += String(repeating: "*", count: 2 * n - 1)
        } else if i == 1 {
            line += "*"
        } else {
            line += "*" + String(repeating: " ", count: 2 * i - 3) + "*"
        }
        print(line)
    }
}

hollowPyramid(5)

Output

Copy
    *
   * *
  *   *
 *     *
*********

9. X-Shape

Diagonals of stars.

Copy
*   *
 * *
  *
 * *
*   *
Copy
func xShape(_ n: Int) {
    for i in 0..<n {
        var line = ""
        for j in 0..<n {
            line += (i == j || i + j == n - 1) ? "*" : " "
        }
        print(line)
    }
}

xShape(5)

Output

Copy
*   *
 * *
  *
 * *
*   *

10. Sandglass

Inverted triangle on top, triangle below.

Copy
*****
 ***
  *
 ***
*****
Copy
func sandglass(_ n: Int) {
    for i in stride(from: n, through: 1, by: -1) {
        let spaces = String(repeating: " ", count: n - i)
        let stars = String(repeating: "*", count: 2 * i - 1)
        print(spaces + stars)
    }
    for i in 2...n {
        let spaces = String(repeating: " ", count: n - i)
        let stars = String(repeating: "*", count: 2 * i - 1)
        print(spaces + stars)
    }
}

sandglass(3)

Output

Copy
*****
 ***
  *
 ***
*****

Conclusion

These 10 Swift patterns bring the count across all three languages (Dart, Go, Swift) to a comparable level. Combined with Python, you now have a solid reference for interviews and everyday coding.

Happy coding!

Mihir Pipermitwala

Written by Mihir Pipermitwala

Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.

More about Mihir →
Scroll down to load comments...
Related Blogs
Go JSON v2: A Practical Migration Guide to encoding/json/v2

Go JSON v2: A Practical Migration Guide to encoding/json/v2

Migrate a Go REST API to encoding/json/v2 in 7 steps: struct tags, omitempty, unknown fields, error handling, and jsontext streaming, plus a v1 vs v2 comparison.

GOTUTORIALDEVELOPER TOOLS

November 12, 2026

Unlocking Flutter's Potential: Best Practices for Writing Clean Code

Unlocking Flutter's Potential: Best Practices for Writing Clean Code

Unlock Flutter's potential with clean code. Learn best practices for writing maintainable Dart code, with examples and essential principles.

CLEAN CODECODE BEST PRACTICESCODE MAINTAINABILITYCODE ORGANIZATIONCODE READABILITY

June 02, 2023

Top 9 Local Databases for Flutter: Full Comparison

Top 9 Local Databases for Flutter: Full Comparison

Compare the best local databases for Flutter (Isar, Hive, Sqflite, ObjectBox, Realm, Drift, Floor, CBL, Sembast). Find pros, cons, and performance comparisons.

CODINGFLUTTERFLUTTER LOCAL DATABASESLEARN TO CODENOSQL

April 06, 2023

Related Tutorials
Essential Git Skills: How to Delete Remote Branches

Essential Git Skills: How to Delete Remote Branches

Keep your repository clean and organized. This guide walks you through how to delete both local and remote branches in Git, step by step.

BITBUCKETDELETE LOCAL BRANCHDELETE REMOTE BRANCHGITGIT BRANCH CLEANUP AUTOMATION

June 12, 2024

Show an Offline Message for No Internet in Flutter

Show an Offline Message for No Internet in Flutter

You have to use the 'Connectivity Flutter Package' to achieve this feature on your App. This package helps to know whether your device is online or offline.

CONNECTIVITY PLUSDEPENDENCIESFLUTTERFLUTTER DEVELOPMENTFLUTTER PACKAGES

April 09, 2024

Mastering TabBar & TabBarView in Flutter: A Complete Guide

Mastering TabBar & TabBarView in Flutter: A Complete Guide

Implement TabBar and TabBarView in Flutter step by step — customize tab indicators, enable scrollable tabs, and change tabs programmatically.

CODINGDEFAULT TAB CONTROLLERFLUTTERLEARN TO CODETAB CONTROLLER

July 26, 2023

File Manipulation in Flutter: Best Practices & Examples

File Manipulation in Flutter: Best Practices & Examples

Master Flutter file manipulation — permission management, directory handling, and practical read-write scenarios to elevate your app's file handling.

CODINGFLUTTERFLUTTER DEVELOPMENTFLUTTER FILE OPERATIONFLUTTER PATH PROVIDER

June 30, 2023

Related Recommended Services
Visual Studio Code for the Web

Visual Studio Code for the Web

Build with Visual Studio Code, anywhere, anytime, in your browser.

IDEVISUAL STUDIOVISUAL STUDIO CODEWEB
Renovate | Automated Dependency Updates

Renovate | Automated Dependency Updates

Renovate Bot keeps source code dependencies up-to-date using automated Pull Requests.

AUTOMATED DEPENDENCY UPDATESBUNDLERCOMPOSERGITHUBGO MODULES
Best XML Formatter and XML Beautifier

Best XML Formatter and XML Beautifier

Online XML Formatter will format xml data, helps to validate, and works as XML Converter. Save and Share XML.

XMLXML BEAUTIFIERXML CONVERTERXML FORMATXML FORMATTER
Kubecost | Kubernetes cost monitoring and management

Kubecost | Kubernetes cost monitoring and management

Kubecost started in early 2019 as an open-source tool to give developers visibility into Kubernetes spend. We maintain a deep commitment to building and supporting dedicated solutions for the open source community.

CLOUDKUBECOSTKUBERNETESOPEN SOURCESELF HOSTED
Related Recommended Stories
How GitHub reduced testing time for iOS apps with new runner features

How GitHub reduced testing time for iOS apps with new runner features

Learn how GitHub used macOS and Apple Silicon runners for GitHub Actions to build, test, and deploy our iOS app faster.

IOSGITHUBTESTINGRUNNER
5 ways to transform your workflow using GitHub Copilot and MCP

5 ways to transform your workflow using GitHub Copilot and MCP

Learn how to streamline your development workflow with five different MCP use cases.

AGENT MODECODING AGENTCOPILOTFIGMAGITHUB
One weird trick for powerful Git aliases

One weird trick for powerful Git aliases

Advanced Git Aliases

ALIASALIAS TEMPLATEATLASSIANBITBUCKETGIT
Awesome Python

Awesome Python

An opinionated list of awesome Python frameworks, libraries, software and resources

AWESOMEAWESOME PYTHONCOLLECTIONSGITHUBPYTHON
Related Recommended Tools
Find out what websites are built with - Wappalyzer

Find out what websites are built with - Wappalyzer

Find out the technology stack of any website. Create lists of websites and contacts by the technologies they use.

ADD ONSANALYTICSAPP STOREAPPLEBOOKING
Sourcetree | Free Git GUI for Mac and Windows

Sourcetree | Free Git GUI for Mac and Windows

A Git GUI that offers a visual representation of your repositories. Sourcetree is a free Git client for Windows and Mac.

GITGITHUBGITLABATLASSIANBITBUCKET
Related Recommended Videos