Contents:
- OS: OS X El Capitan v10.11.6
- Xcode: v8.3
Install the latest version of Xcode from iTunes.
You can check swift version by running the following in your terminal:
$ xcrun swift -version
Apple Swift version 3.1 (swiftlang-802.0.48 clang-802.0.38)
Target: x86_64-apple-macosx10.9
- Open Xcode.
- Open a playground.
import UIKit
var str = "Hello, playground" // "Hello, playground"
let str = "This is constant"
let other_str: String = "Another constant"
var gender: Character
var address: String
var age: Int
var price: Float
var rate: Double
var active: Bool
var street: String = "This is a variable"
var str = "This is a variable"
var str: String?
str = "foo"
print(str!) // "foo\n"
var foo = "Test string"
print("Some string") // => "Some string\n"
print(foo)
print(10 * 50)
print("This is interpolated with \(foo)")
var array3 = ["Apple", "Pear", "Orange"]
array3.append("Cherry") // ["Apple", "Peach", "Orange", "Cherry"]
array3.insert("Prune", at: 2) // ["Apple", "Peach", "Prune", "Orange", "Cherry"]
array3 // ["Apple", "Peach", "Prune", "Orange", "Cherry"]
var dictionary1: Dictionary<String, Int>
var dictionary2: [String: Int]
var dictionary3 = ["Apple": 3, "Pear": 8, "Orange": 11] // ["Pear": 8, "Orange": 11, "Apple": 3]
dictionary3.removeValue(forKey: "Pear") // 8
dictionary3 // ["Orange": 11, "Apple": 3]
var set1: Set<String>
var set2 = Set<String>() // Set([])
var set3: Set<String> = ["Apple", "Pear", "Orange"] // {"Pear", "Orange", "Apple"}
set3.insert("Prune")
set3 // {"Pear", "Orange", "Apple", "Prune"}
set3.remove("Pear") // "Pear"
set3 // {"Orange", "Apple", "Prune"}
set3.contains("Orange") // true
import Foundation
var currency = ("EUR", 0.81) // (.0 "EUR", .1 0.8100000000000001)
var email = ("Bart Jacobs", "[email protected]") // (.0 "Bart Jacobs", .1 "[email protected]")
var currency = (name: "EUR", rate: 0.81) // (.0 "EUR", .1 0.8100000000000001)
currency.name // "EUR"
currency.rate // 0.8100000000000001
if foo > bar {
print("something")
} else if foo < bar {
print("something else")
} else {
print("nothing")
}
let a = 10
switch a {
case 0:
print("a is equal to 0")
case 1:
print("a is equal to 1")
default:
print("a has another value")
}
let a = 10
switch a {
case 0..<5:
print("The value of a lies between 0 and 4.")
case 5...10:
print("The value of a lies between 5 and 10.") // "The value of a lies between 5 and 10.\n"
default:
print("The value of a is greater than 10.")
}
We can match patterns as below:
let latlng = (34.15, -78.03)
switch latlng {
case (0, 0):
print("We're at the center of the planet.")
case (0...90, _):
print("We're in the Northern hemisphere.") // "We're in the Northern hemisphere.\n"
case (-90...0, _):
print("We're in the Southern hemisphere.")
default:
print("The coordinate is invalid.")
}
Value binding can be done as follows:
var response = (200, "OK")
switch response {
case (200..<400, let description):
print("The request was successful with description \(description).") // "The request was successful with description OK.\n"
case (400..<500, let description):
print("The request was unsuccessful with description \(description).")
default:
print("The request was unsuccessful with no description.")
}
let numbers = [1, 2, 3, 5, 8]
for number in numbers {
print("number is equal to \(number)")
}
var bids = ["Tom": 100, "Bart": 150, "Susan": 120]
for (name, bid) in bids {
print("\(name)'s bid is $\(bid).")
}
while foo < bar {
print("something")
}
repeat {
print("something")
} while foo < bar
func printHelloWorld() {
print("Hello World!")
}
printHelloWorld() // Hello World!
func printMessage(message: String) {
print(message)
}
printMessage(message: "OK!") // OK!
You can make label optional when calling the functions.
func printMessage(_ message: String) {
print(message)
}
printMessage("OK!") // OK!
import UIKit
func printDate(date: Date, format: String = "MM/dd/YYYY") {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
print(dateFormatter.string(from: date))
}
printDate(date: Date()) // 04/12/2017
printDate(date: Date(), format: "MM/dd") // 04/12
import UIKit
func formatDate(date: Date, format: String = "MM/dd/YYYY") -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: date)
}
let formattedDate = formatDate(date: Date())
print(formattedDate) // 04/12/2017
import UIKit
func timeComponentsFromDate(_ date: Date) -> (hour: Int, minute: Int, second: Int) {
let dateComponents = Calendar.current.dateComponents([.hour, .minute, .second], from: date)
let hour = dateComponents.hour
let minute = dateComponents.minute
let second = dateComponents.second
return (hour ?? 0, minute ?? 0, second ?? 0)
}
print(timeComponentsFromDate(Date())) // (hour: 1, minute: 5, second: 15)
let components = timeComponentsFromDate(Date())
print(components.hour) // 1
print(components.minute) // 5
print(components.second) // 15
import UIKit
func timeComponentsFromDate(_ date: Date) -> (Int, Int, Int) {
let dateComponents = Calendar.current.dateComponents([.hour, .minute, .second], from: date)
let hour = dateComponents.hour
let minute = dateComponents.minute
let second = dateComponents.second
return (hour ?? 0, minute ?? 0, second ?? 0)
}
print(timeComponentsFromDate(Date())) // (1, 6, 51)
let components = timeComponentsFromDate(Date())
print(components.0) // 1
print(components.1) // 6
print(components.2) // 51
func printMessage(message msg: String) {
print(msg)
}
printMessage(message: "Hello!") // Hello!
func printMessage(message msg: String) {
var msg = msg
msg = "New value"
print(msg)
}
printMessage(message: "Hello!") // New value
func sum(_ args: Int...) -> Int {
var result = 0
for a in args {
result += a
}
return result
}
sum(1, 3, 4, 5) // 13
func prefixString(_ string: inout String, prefix: String) {
string = prefix + string
}
var input = "world!"
prefixString(&input, prefix: "Hello ")
input // "Hello world!"
func printMessage(_ msg: String) {
let a = "Hello world!"
func printHelloWorld(){
print(a)
}
printHelloWorld()
}
printMessage("") // Hello world!
func prefixHello(_ msg: String) {
var msg = "Hello " + msg
print(msg)
}
func sayHello(_ msg: String, function: (String) -> ()) {
function(msg)
}
sayHello("JD", function: prefixHello) // Hello JD
import UIKit
var states = ["California", "New York", "Texas", "Alaska"]
let abbreviatedStates = states.map({ (state: String) -> String in
let index = state.index(state.startIndex, offsetBy: 2)
return state.substring(to: index).uppercased()
})
print(abbreviatedStates) // ["CA", "NE", "TE", "AL"]
You can also use shorthand argument names, $0
, $1
, etc.
import UIKit
var states = ["California", "New York", "Texas", "Alaska"]
let abbreviatedStates = states.map({ $0.substring(to: $0.index($0.startIndex, offsetBy: 2)).uppercased() })
print(abbreviatedStates) // ["CA", "NE", "TE", "AL"]
class Person {
var firstName: String?
var lastName: String?
let birthPlace: String
init(birthPlace: String) {
self.birthPlace = birthPlace
}
func fullName() -> String {
var parts: [String] = []
if let firstName = self.firstName {
parts += [firstName]
}
if let lastName = self.lastName {
parts += [lastName]
}
return parts.joined(separator: " ")
}
}
let john = Person(birthPlace: "USA")
john.birthPlace // "USA"
john.firstName = "John"
john.lastName = "Cena"
john.fullName() // "John Cena"
class Student: Person {
}
let student = Student(birthPlace: "India")
student.birthPlace // "India"
Launch Xcode and select Create a new Xcode Project. From the iOS section, choose Single View Application template and click Next.
Now, name the project and set language to Swift. Select the Team. Make sure devise is set to iPhone and all the checkboxes at the bottom are unchecked. Click Next to continue.
Select location where the project will be saved and click Create.
- Setup
- Adding your account to Xcode
- Creating your team provisioning profile
- Launching your app on Devices
- Enabling app services
In your Xcode project, open up Main.storyboard and drag in a Table View object from bottom right panel of the window. If you run the app at this point, you should see an empty table view.
Now, we need to setup a delegate and data source for the table view. Hold ctrl key, click on the table view, click on radio button to the right of Outlets -> dataSource, drag the + sign to ViewController object in storyboard's hierarchy.
Repeat above steps for Outlets -> delegate.
// ViewController.swift
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section:Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "MyTestCell")
cell.textLabel?.text = "Row #\(indexPath.row)"
cell.detailTextLabel?.text = "Subtitle #\(indexPath.row)"
return cell
}
}
Now, running your app should display a table with 10 rows. Each row will have a title Row #*, and a subtitle Subtitle #*.
- http://www.ios-blog.co.uk/tutorials/swift/developing-ios8-apps-using-swift-part-2-connect-to-the-itunes-search-api/
- http://www.ios-blog.co.uk/tutorials/swift/developing-ios8-apps-using-swift-part-3-best-practices/
- http://www.ios-blog.co.uk/tutorials/swift/swift-cheat-sheet/
- http://www.ios-blog.co.uk/tutorials/swift/developing-ios8-apps-using-swift-part-4-adding-interactions/
- http://www.ios-blog.co.uk/tutorials/swift/developing-ios8-apps-using-swift-part-5-async-image-loading-and-caching/
- http://www.ios-blog.co.uk/tutorials/swift/developing-ios8-apps-using-swift-create-a-to-do-application/
- http://www.ios-blog.co.uk/tutorials/swift/developing-ios8-apps-using-swift-part-6-interaction-with-multiple-views/
- http://www.ios-blog.co.uk/tutorials/swift/getting-repl-read-eval-print-loop-in-ios8-swift-and-terminal/
- http://www.ios-blog.co.uk/tutorials/swift/developing-ios8-apps-using-swift-part-7-animations-audio-and-custom-table-view-cells/
- http://www.ios-blog.co.uk/tutorials/swift/how-to-make-an-app-hello-world/
- http://www.ios-blog.co.uk/tutorials/swift/introduction-to-ios8-swift-series-constant-and-variables/
- http://www.ios-blog.co.uk/tutorials/swift/introduction-to-ios8-swift-series-strings/
- http://www.ios-blog.co.uk/tutorials/swift/quick-tip-dispatch_once-singleton-model-in-swift/
- http://www.ios-blog.co.uk/tutorials/swift/swift-variables-and-constants/
- http://www.ios-blog.co.uk/tutorials/objective-c/base64-decoding-in-ios-7-objective-c-and-ios8-swift/
- http://www.ios-blog.co.uk/tutorials/swift/computed-properties-in-swift/
- http://www.ios-blog.co.uk/tutorials/objective-c/how-to-detect-screenshots-in-objective-c-and-swift-like-snapchat/
- http://www.ios-blog.co.uk/tutorials/swift/quick-tip-implementing-uialertview-in-swift/
- http://www.ios-blog.co.uk/tutorials/swift/connect-your-swift-application-to-parse-com/
- http://www.ios-blog.co.uk/tutorials/swift/swift-create-user-sign-up-based-app-with-parse-com-using-pfuser/
- http://www.ios-blog.co.uk/tutorials/swift/swift-create-a-login-app-with-parse-com-pfuser-keychain-locksmith/
- http://www.ios-blog.co.uk/tutorials/swift/enumerations/
- http://www.ios-blog.co.uk/tutorials/swift/swift-how-to-send-a-post-request-to-a-php-script/
- http://www.ios-blog.co.uk/tutorials/swift/swift-nstimer-tutorial-lets-create-a-counter-application/
- http://www.ios-blog.co.uk/tutorials/swift/swift-tuples/
- http://www.ios-blog.co.uk/tutorials/swift/swift-type-annotations/
- http://www.ios-blog.co.uk/tutorials/swift/programming-introduction/
- http://www.ios-blog.co.uk/tutorials/swift/check-api-availability-with-swift-2/
- http://www.ios-blog.co.uk/tutorials/swift/swift-2-0-print-repeat-while/
- http://www.ios-blog.co.uk/tutorials/swift/introduction-to-uistackview/
- http://www.ios-blog.co.uk/tutorials/swift/swift-2-a-quick-look-at-print-vs-println-vs-nslog/
- http://www.ios-blog.co.uk/tutorials/swift/how-to-creating-ascii-art/
- http://www.ios-blog.co.uk/tutorials/swift/using-nsuserdefaults-with-swift/
- http://www.ios-blog.co.uk/tutorials/swift/editable-uitextfield-inside-a-uialertcontroller/
- http://www.ios-blog.co.uk/tutorials/swift/introduction-to-guard-syntax/
- http://www.ios-blog.co.uk/tutorials/swift/core-data-p1/
- http://www.ios-blog.co.uk/tutorials/swift/create-today-widget-extension/
- http://www.ios-blog.co.uk/tutorials/swift/core-data-p2/
- http://www.ios-blog.co.uk/tutorials/swift/contacts-framework-p1/
- http://www.ios-blog.co.uk/tutorials/swift/contacts-framework-p2/
- http://www.ios-blog.co.uk/tutorials/swift/parse-json-deserialization/
- http://www.ios-blog.co.uk/tutorials/swift/detecting-low-power-mode/
- http://www.ios-blog.co.uk/tutorials/swift/swift-timer-tutorial-create-a-counter-timer-application-using-nstimer/
- https://www.udemy.com/learn-ios-programming-from-scratch/
- https://www.udemy.com/the-art-of-real-ios-programming/
- https://designthencode.com/scratch/
- http://codewithchris.com/how-to-make-iphone-apps-with-no-programming-experience/
- http://www.appcoda.com/ios-programming-course/
- https://www.codeschool.com/courses/try-ios
- https://teamtreehouse.com/tracks/ios-development-with-swift
- https://www.raywenderlich.com/114148/learn-to-code-ios-apps-with-swift-tutorial-1-welcome-to-programming
- https://developer.apple.com/library/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/index.html?utm_source=statuscode&utm_medium=email
- https://developer.apple.com/swift/
- https://www.udacity.com/course/intro-to-ios-app-development-with-swift--ud585
- http://www.macworld.co.uk/how-to/mac-software/best-way-learn-swift-2-iphone-app-development-advice-resources-3-3597812/
- http://www.learnswift.tips
- http://www.tutorialspoint.com/swift/
- http://code.tutsplus.com/series/swift-from-scratch--cms-709 (Delegation and Properties)
Important iOS (Swift and objective C) code for follow following links
Custom camera in swift
Custom camera in objective C
Image pick from gallery in swift
Image pick from gallery in objective C
Download image from URL in swift using async method
Formatted string currency value in swift
Set custom protocol and delegate method in swift
Set block in swift
Set Swipe gesture in swift
Set root view controller in swift
Set outlet collection in swift
Set Timer in swift
Set Root view controller in swift
Get UUID String in swift
Set Status bar background color in swift
Rate Application
Hide keyboard when you press keyboard return button in swift
Show loader or activity indicator in swift
Send multipart data using Alamofire in swift
Open dialoguebox in swift
Pass any value from one viewcontroller to another view controller
Set placeholder text in UITextView
Send pdf file in email in swift
Website URL Validation in swift
Convert Date to string and string to date in swift
Convert date in milliseconds in swift
Convert UIImage in Base64 String in swift
Set Left and right image in UITestfield of swift
Set Hyperlink button in swift
Find iphone screen width and height in swift
Set shadow in UIView
Set Done bar in numberpad of UITextField in swift
Set placeholder text color in swift
Set Padding in UITextField
Change date formate to another formate in swift
Trim string in ios swift
Set Email validation in swift
Set custom tableview in ios swift
Set dynamic height of UITableview cell in ios
Set Value in User Defaults in swift
Generate .pem file for ios push notification
How do ios push notification work
Set more than one marker in google map in ios
Find UDID for your iphone Device
Float number formatting in swift
Difference between development and distribution provisioning profile in ios
Navigate from one view controller to another view controller in swift
Image in circle frame in swift
Difference between ? and ! in swift
Difference between ViewDidload and loadView in swift
Change right to left view when change language in swift
Infinite scroll in collectionview swift
Implement Localization in iOS
Integrate cocoapod in xcode project
For loop in swift 3.0 or later
Block in objective C
Sharing text image or any file in swift
Copy text with iOS
Google place autocomplete search controller in swift 3 or later