on bce304a help sign in
268 lines 8.2 kB history raw
1class Person {
2// We can define class property here
3var age = 25
4// Implement Class initializer. Initializers are called when a new object of this class is created
5init() {
6 print(“A new instance of this class Person is created.”)
7 }
8}
9// We can now create an instance of class Person - an object - by putting parentheses after the class name
10let personObj = Person()
11// Once an instance of Person class is created we can access its properties using the dot “.” syntax.
12print(“This person age is \(personObj.age)”)
14import Foundation
15class Friend : Comparable {
16 let name : String
17 let age : Int
19 init(name : String, age: Int) {
20 self.name = name
21 self.age = age
22 }
24func < (lhs: Friend, rhs: Friend) -> Bool {
25 return lhs.age < rhs.age }; func > (lhs: Friend, rhs: Friend) -> Bool {
26 return lhs.age > rhs.age
28func == (lhs: Friend, rhs: Friend) -> Bool {
29 var returnValue = false
30 if (lhs.name == rhs.name) && (lhs.age == rhs.age)
31 {
32 returnValue = true
33 }
34 return returnValue
37 let friend1 = Friend(name: "Sergey", age: 35)
38 let friend2 = Friend(name: "Sergey", age: 30)
40 print("Compare Friend object. Same person? (friend1 == friend2)")
42func sayHelloWorld() {
43 print("Hello World")
45// Call function
46sayHelloWorld()
48func printOutFriendNames(names: String...) {
50 for name in names {
52 print(name)
53 }
56// Call the printOutFriendNames with two parameters
57printOutFriendNames("Sergey", "Bill")
58// Call the function with more parameters
59printOutFriendNames("Sergey", "Bill", "Max")
61let simpleClosure = {
62 print("From a simpleClosure")
64// Call closure
65simpleClosure()
67let fullName = { (firstName:String, lastName:String)->String in
68 return firstName + " " + lastName
70// Call Closure
71let myFullName = fullName("Sergey", "Kargopolov")
72print("My full name is \(myFullName)")
74let myDictionary = [String:String]()
75// Another way to create an empty dictionary
76let myDictionary2:[String:String] = [:]
77// Keys in dictionary can also be of type Int
78let myDictionary3 = [Int:String]()
80var myDictionary = ["first_name": "Sergey", "last_name": "Kargopolov"]
81// print to preview
82print(myDictionary)
83// Add a new key with a value
84myDictionary["user_id"] = "f5h7ru0tJurY8f7g5s6fd"
85// We should now have 3 key value pairs printed
86print(myDictionary)
88var myDictionary = ["first_name": "Sergey", "last_name": "Kargopolov"]
89// Loop through dictionary keys and print values
90for (key,value) in myDictionary {
91 print("\(key) = \(value)")
93 class Friend {
94 let name : String
95 let age : Int
97 init(name : String, age: Int) {
98 self.name = name
99 self.age = age
100 }
103 var friends:[Friend] = []
105 let friend1 = Friend(name: "Sergey", age: 30)
106 let friend2 = Friend(name: "Bill", age: 35)
107 let friend3 = Friend(name: "Michael", age: 21)
109 friends.append(friend1)
110 friends.append(friend2)
111 friends.append(friend3)
113 printFriends(friends: friends)
115 // Get sorted array in descending order (largest to the smallest number)
116 let sortedFriends = friends.sorted(by: { $0.age > $1.age })
117 printFriends(friends: sortedFriends)
119 // Get sorted array in ascending order (smallest to the largest number)
120 let sortedFriendsAscendingOrder = friends.sorted(by: { $0.age < $1.age })
121 printFriends(friends: sortedFriendsAscendingOrder)
124 func printFriends(friends: [Friend])
125 {
126 for friendEntry in friends {
127 print("Name: \(friendEntry.name), age: \(friendEntry.age)")
128 }
129 }
131import UIKit
132class ViewController: UIViewController {
133override func viewDidLoad() {
134 super.viewDidLoad()
136override func viewWillAppear(_ animated: Bool) {
137 super.viewWillAppear(animated)
139 // Create destination URL
140 let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
141 let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")
143 //Create URL to the source file you want to download
144 let fileURL = URL(string: "https://s3.amazonaws.com/learn-swift/IMG_0001.JPG")
146 let sessionConfig = URLSessionConfiguration.default
147 let session = URLSession(configuration: sessionConfig)
149 let request = URLRequest(url:fileURL!)
151 let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
152 if let tempLocalUrl = tempLocalUrl, error == nil {
153 // Success
154 if let statusCode = (response as? HTTPURLResponse)?.statusCode {
155 print("Successfully downloaded. Status code: \(statusCode)")
156 }
158 do {
159 try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
160 } catch (let writeError) {
161 print("Error creating a file \(destinationFileUrl) : \(writeError)")
162 }
164 } else {
165 print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
166 }
167 }
168 task.resume()
170 }
173 do {
175 // Convert JSON Object received from server side into Swift NSArray.
176 // Note the use "try"
177 if let convertedJsonIntoArray = try JSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
178 }
180 } catch let error as NSError {
181 print(error.localizedDescription)
182 }
184DispatchQueue.global(qos: .userInitiated).async {
185 // Do some time consuming task in this background thread
186 // Mobile app will remain to be responsive to user actions
188 print("Performing time consuming task in this background thread")
190 DispatchQueue.main.async {
191 // Task consuming task has completed
192 // Update UI from this block of code
193 print("Time consuming task has completed. From here we are allowed to update user interface.")
194 }
195 }
197import UIKit
198class ViewController: UIViewController {
200 override func viewDidLoad() {
201 super.viewDidLoad()
202 // Do any additional setup after loading the view, typically from a nib.
204 let button = UIButton(type: UIButtonType.system) as UIButton
206 let xPostion:CGFloat = 50
207 let yPostion:CGFloat = 100
208 let buttonWidth:CGFloat = 150
209 let buttonHeight:CGFloat = 45
211 button.frame = CGRect(x:xPostion, y:yPostion, width:buttonWidth, height:buttonHeight)
213 button.backgroundColor = UIColor.lightGray
214 button.setTitle("Tap me", for: UIControlState.normal)
215 button.tintColor = UIColor.black
216 button.addTarget(self, action: #selector(ViewController.buttonAction(_:)), for: .touchUpInside)
218 self.view.addSubview(button)
219 }
221 func buttonAction(_ sender:UIButton!)
222 {
223 print("Button tapped")
224 }
226 override func didReceiveMemoryWarning() {
227 super.didReceiveMemoryWarning()
228 // Dispose of any resources that can be recreated.
229 }
234import UIKit
235class ViewController: UIViewController {
237 override func viewDidLoad() {
238 super.viewDidLoad()
240 //Create Activity Indicator
241 let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
243 // Position Activity Indicator in the center of the main view
244 myActivityIndicator.center = view.center
246 // If needed, you can prevent Acivity Indicator from hiding when stopAnimating() is called
247 myActivityIndicator.hidesWhenStopped = false
249 // Start Activity Indicator
250 myActivityIndicator.startAnimating()
252 // Call stopAnimating() when need to stop activity indicator
253 //myActivityIndicator.stopAnimating()
256 view.addSubview(myActivityIndicator)
257 }
259 override func didReceiveMemoryWarning() {
260 super.didReceiveMemoryWarning()
261 }