Programming Tutorials

  • View all tutorials
  • ,
    Learn the basics of Swift
    Swift is a new programming language created by Apple for use in iOS, OS X, watchOS, and tvOS app development. It is a general-purpose, type-safe programming language. Below we'll go over some of the basics so you can get comfortable with the syntax and start solving Coderbyte challenges in Swift.

    Variables

    Swift allows you to declare variables and constants very easily. Constant values cannot change, and they are declared using the let keyword, while variable are declared using the var keyword.
    // constant cannot change
    let maxNumber = 100
    maxNumber = 200 // cannot do this, compile-time error
    
    // variable
    var someVar = 123
    someVar = 456
    
    You can optionally specify a type for your variables like so:
    var someStr: String
    someStr = "Hello world"
    
    var someInt: Int
    someInt = 100
    someInt = "Will this work" // error
    

    String manipulation

    To access certain characters in a string, we'll need to use string indexing, which in Swift may look a bit odd at first.
    var str: String
    str = "Hello world!"
    
    print(str[str.startIndex]) // => H
    print(str[str.startIndex.advancedBy(1)]) // => e
    print(str[str.startIndex.advancedBy(4)]) // => o
    print(str[str.startIndex.successor()]) // => e
    
    // get length of string
    print(str.characters.count) // => 12
    
    To loop through a string in Swift you can use the following combination of character methods:
    var str: String
    str = "Hello world!"
    
    for index in str.characters.indices {
      print(str[index])
    } 
    
    // loop above outputs "Hello world!"
    
    You can easily add or remove characters from a string using Swift's built-in methods:
    var str: String
    str = "Hello world!"
    
    str.insertContentsOf(" Goodbye World?".characters, at: str.endIndex)
    print(str) // => Hello world! Goodbye World?
    
    // create a range using .. half-open range operator and then remove it
    str.removeRange(str.endIndex.advancedBy(-7)..<str.endIndex)
    print(str) // => Hello world! Goodbye
    

    Arrays

    You can easily define and loop through arrays in Swift:
    var people = ["Dan", "Mike", "Jen"]
    
    for i in 0..<people.count {
      print("Hello \(people[i])")
    }
    
    // loop above outputs
    // Hello Dan
    // Hello Mike
    // Hello Jen
    
    In the loop above we iterate over a range using the half-open range operator. We can combine logical operators within our loop as well:
    var nums = [1, 4, -6, -2, 0, -12]
    
    for i in 0..<nums.count {
      if nums[i] > 0 || nums[i] < -5 {
        print(nums[i])
      }
    }
    
    // loop above outpus
    // 1
    // 4
    // -6
    // -12
    
    You can add and remove elements from an array easily in Swift as well:
    // specify the type of array it is
    var nums: [Int] = [1, 2, 3, 4, 5]
    
    // two ways to append elements
    nums.append(6)
    nums += [7, 8, 9]
    
    print(nums) // => [1, 2, 3, 4, 5, 6, 7, 8, 9]
    print(num[2]) // => 3
    
    nums.insert(0, atIndex: 2)
    print(nums) // => [1, 2, 0, 3, 4, 5, 6, 7, 8, 9]
    
    var removed = nums.removeAtIndex(0)
    print(removed) // => 1
    print(nums) // => [2, 0, 3, 4, 5, 6, 7, 8, 9]
    
    Getting a certain range from an array can be done using the range (..) operator:
    var arr = [1, 2, 3, 4, 5]
    print(arr[1...3]) // => [2, 3, 4]
    

    Functions

    Functions in Swift begin with the func keyword and, if taking in parameters, must specify their types. If your function is returning a value, it also needs a return type. Below is an example that takes in a string and an integer, and returns a string array.
    func Nstrings(str: String, _ num: Int) -> [String] {
      var result: [String] = []
      for i in 1...num {
        result.append(str)
      }
      return result
    }
    
    print(Nstrings("hello", 3)) // => ["hello", "hello", "hello"]
    
    The underscore that's used in the function declaration before num is there because in Swift, you can specify an external parameter name and a local parameter name. Unique external names simply make the code more readable and easier to understand. The function above could be written as below:
    func Nstrings(str: String, multiplyBy num: Int) -> [String] {
      var result: [String] = []
      for i in 1...num {
        result.append(str)
      }
      return result
    }
    
    print(Nstrings("hello", multiplyBy: 3)) // => ["hello", "hello", "hello"]
    
    If you are not sure how many parameters you will pass into a function, there is a feature in Swift called Variadic parameters. Below is this feature in action via the (...) operator in the function declaration:
    // pass in any number of parameters to calculate the mean
    func mean(nums: Double...) -> Double {
        var total: Double = 0
        for i in nums {
            total += i
        }
        return total / Double(nums.count)
    }
    
    print(mean(1, 2, 3, 4)) // => 2.5
    print(mean(10, 12, 45, 102, 105, 203, 1000)) // => 211.0
    
    Below are some extra resources to help you learn and practice coding in Swift: TutorialsPoint tutorial Swift 2 Tutorial: A Quick Start Learn Swift Tips
    mrdaniel wrote this tutorial on 5/23/16 | apple, swift
    Comments
    Log in to submit a comment.