Skip to content
  • Home
  • About us
  • Contact
  • Privacy Policy
  • Disclaimer
  • Swift Online Compiler
iOS Interview Questions and Tutorials

iOS Interview Questions and Tutorials

2D Array in Swift

Posted on November 1, 2023November 23, 2023 By Sid No Comments on 2D Array in Swift
2D array in Swift examples

Q.1 Given a matrix find row-wise sum.
Sol>

var matrix = [
[1, -1, 4, 3],
[2, 6, -1, -2],
[6, -1, 0, 3]
]

func rowWiseSum(matrix: [[Int]]) {

    for row in 0..<matrix.count {

        var sum = 0

        for col in 0..<matrix[row].count {

            sum += matrix[row][col]

        }

        print(sum)

    }

}

rowWiseSum(matrix: matrix)

o/p-
7
5
8

Q. Given a matrix find column-wise sum.
Sol>

var matrix = [
[1, -1, 4, 3],
[2, 6, -1, -2],
[6, -1, 0, 3]
]

Method – 1

func columnWiseSum(matrix: [[Int]]) {

    let rowCount = matrix.count

    let colCount = matrix[0].count

        for col in 0..<colCount {

        var sum = 0

        for row in 0..<rowCount {

            sum += matrix[row][col]

        }

        print(sum)

    }

}

columnWiseSum(matrix: matrix)

0/p-
9
4
3
4

Method- 2

func columnWiseSum(matrix: [[Int]]) -> [Int] {

    let rowCount = matrix.count

    let colCount = matrix[0].count

    var columnSums = [Int](repeating: 0, count: colCount)

    for row in matrix {

        print(“row: \(row.enumerated())“)

        for (col, element) in row.enumerated() {

            columnSums[col] += element

        }

    }

    return columnSums

}

rowWiseSum(matrix: matrix)

o/p-

9
4
3
4

Blog Tags:2D Array, 2d Array in Swift, DSA in Swift

Post navigation

Previous Post: User Defaults in Swift
Next Post: Associated Types in Swift

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Asked iOS Interview Questions

  • Top iOS Interview Questions and Answers

Categories

  • Associated Types(7)
  • Blog
  • Dictionary in Swift(20)
  • Initializers
  • Property Wrapper
  • Singleton in Swift
  • User Defaults(4)
  • XCode 15 Errors

Recent Comments

  1. Sid on Cycle inside MyApp; building could produce unreliable results
  2. Anominous on Cycle inside MyApp; building could produce unreliable results
  3. Aisha on @objc Attribute in Swift

Recent Posts

  • Enums in Swift: Brief Explanation with Code Examples
  • Higher-Order Functions in Swift: Brief Explanation with Code Examples
  • Mutability in Structs and Classes in Swift
  • Delegate Pattern in Swift
  • resueIdentifier in Swift

DSA in Swift

  • 2D Array in Swift: Interview Questions

Copyright © 2025 iOS Interview Questions and Tutorials.

Powered by PressBook WordPress theme