2// We can define class property here
4// Implement Class initializer. Initializers are called when a new object of this class is created
6 print(“A new instance of this class Person is created.”)
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)”)
15class Friend : Comparable {
19 init(name : String, age: Int) {
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)
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)")
48func printOutFriendNames(names: String...) {
56// Call the printOutFriendNames with two parameters
57printOutFriendNames("Sergey", "Bill")
58// Call the function with more parameters
59printOutFriendNames("Sergey", "Bill", "Max")
62 print("From a simpleClosure")
67let fullName = { (firstName:String, lastName:String)->String in
68 return firstName + " " + lastName
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"]
83// Add a new key with a value
84myDictionary["user_id"] = "f5h7ru0tJurY8f7g5s6fd"
85// We should now have 3 key value pairs printed
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)")
97 init(name : String, age: Int) {
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])
126 for friendEntry in friends {
127 print("Name: \(friendEntry.name), age: \(friendEntry.age)")
132class ViewController: UIViewController {
133override func 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 {
154 if let statusCode = (response as? HTTPURLResponse)?.statusCode {
155 print("Successfully downloaded. Status code: \(statusCode)")
159 try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
160 } catch (let writeError) {
161 print("Error creating a file \(destinationFileUrl) : \(writeError)")
165 print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
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 {
180 } catch let error as NSError {
181 print(error.localizedDescription)
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.")
198class ViewController: UIViewController {
200 override func 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)
221 func buttonAction(_ sender:UIButton!)
223 print("Button tapped")
226 override func didReceiveMemoryWarning() {
227 super.didReceiveMemoryWarning()
228 // Dispose of any resources that can be recreated.
235class ViewController: UIViewController {
237 override func 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)
259 override func didReceiveMemoryWarning() {
260 super.didReceiveMemoryWarning()
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list