Advertisement
Guest User

swift lesson 1

a guest
Jul 11th, 2018
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 7.80 KB | None | 0 0
  1. //: Playground - noun: a place where people can play
  2.  
  3. var x = 3 // a mutable variable
  4. x = 4
  5.  
  6. let y = 4 // an immutable constant
  7. //y = 5 // error because y is a let so we cannot change it
  8.  
  9. var myInt:Int = 90 // explicit type declaration
  10.  
  11. var myDouble:Double = 3.9
  12.  
  13. var myFloat:Float
  14.  
  15. // Int (and Int8, Int16, Int32, Int64), Double (and Float) , String, Bool, Character
  16.  
  17.  
  18. var z = x + y
  19.  
  20. // we CANNOT implicitly preform math operations between different number types
  21. var addDouble = myDouble + Double(myInt)
  22. var addInt = Int(myDouble) + myInt
  23.  
  24.  
  25. typealias MyString = String
  26. let myString:MyString = "my string with typealias"
  27.  
  28. typealias Long = Int64
  29. let myLong:Long = 69541235
  30.  
  31. var num1,num2,num3:Int
  32. num1 = 4
  33. num2 = 5
  34. num3 = num1 * num2
  35.  
  36. print("num3 is \(num3)") // string interpolation
  37.  
  38. // class work
  39. // 1. define the radius of a cricle and calculate the circumference of the circle
  40. let radius:Double = 5
  41. var cir = 2 * Double.pi * radius
  42. print("the circumference is \(cir)")
  43.  
  44. // 2. define 2 sides of a rectangle and calculate the area and parimeter
  45. let side1 = 9
  46. let side2 = 10
  47. let area = side1 * side2
  48. let per = 2 * (side1 + side2)
  49. print("the parimeter is \(per)")
  50. print("the eara is \(area)")
  51.  
  52. // conditions
  53.  
  54. if x < y {
  55.     print("x is smaller than y")
  56. }
  57. else if x > y {
  58.     print("x is greater than y")
  59. }
  60. else{
  61.     print("x is equal to y")
  62. }
  63.  
  64.  
  65. switch myInt {
  66.     case 0:
  67.         print("myInt is 0")
  68.     case 2:
  69.         print("myInt is 2")
  70.     case 3..<10:
  71.         print("myInt is in 3..<10")
  72.     default:
  73.         print("myInt is not 2 and not 0")
  74. }
  75.  
  76. let st = "hello"
  77. switch st {
  78.     case "hi":
  79.         print("hi")
  80.         fallthrough // fallthrough makes the next case activate
  81.     case "how are you":
  82.         print("how are you?")
  83.     default:
  84.         print("I don't care")
  85. }
  86.  
  87.  
  88. // optionals
  89. // note that 'nil' is like 'null' in java
  90. //var myOptionalString:String? = nil
  91. var myOptionalString:String? = "the string"
  92.  
  93. var myNonOptionalString = "the string"
  94. myNonOptionalString.append("A")
  95. print("non optional: \(myNonOptionalString)")
  96.  
  97. myOptionalString?.append("A")
  98. print("optional: \(myOptionalString)")
  99. //myOptionalString!.append("A") // this is a force - unwrap. dangerous because we might have nil
  100.  
  101. var anotherOptional:String! // we assume that when this variable is used that is has value (isn't nil). so then we don't need to use ? or !
  102. // like writing anotherOptional! everywhere we use it
  103. anotherOptional = "hi there"
  104.  
  105. anotherOptional.append("A")
  106.  
  107.  
  108. if myOptionalString != nil {
  109.     print("optional: \(myOptionalString!)")
  110. }
  111.  
  112.  
  113. // for this code to work it needs to be in a function
  114. //guard let safeValue = myOptionalString else{
  115. //    print("myOptionalString is nil")
  116. //    return // cannot have return in the global scop0e of the playground
  117. //}
  118.  
  119.  
  120. // loops
  121.  
  122. // while and do-while are like java (we don't need parentheses)
  123.  
  124. // for loops
  125. for i in 1..<10 { // numbers from 1 to 10 (NOT including 10)
  126.     print(i)
  127. }
  128.  
  129. for i in 1...10 { // numbers from 1 to 10 (including 10)
  130.     print(i)
  131. }
  132.  
  133. let numsArr = [10,20,30,40,50]
  134.  
  135. for num in numsArr {
  136.     print(num)
  137. }
  138.  
  139. for index in numsArr.indices {
  140.     print(numsArr[index])
  141. }
  142.  
  143. let nameDict = ["key 1":"val 1","key 2":"val 2","key 3":"val 3"]
  144.  
  145. for entry in nameDict{
  146.     print("key \(entry.key), value \(entry.value)")
  147. }
  148.  
  149. for key in nameDict.keys{
  150.     print(key)
  151. }
  152.  
  153. for value in nameDict.values{
  154.     print(value)
  155. }
  156.  
  157. for (key, value) in nameDict{
  158.     print("key \(key), value \(value)")
  159. }
  160.  
  161. for _ in 1..<5{ // _ is instead of a name for the variable since we don't need to use the variable
  162.     print("in loop")
  163. }
  164.  
  165.  
  166. // collections
  167.  
  168. // tuple
  169. var myTup = ("hello", 3)
  170. print(myTup.0)
  171. myTup.1 = 4
  172.  
  173. var namedTup = (name:"the name", age:26, favFood:"Pizza")
  174. namedTup.name = "tzahi meaher"
  175.  
  176. var tup:(char: Character, dub: Double)
  177. tup.char = "A"
  178. tup.dub = 3.9
  179.  
  180. print(tup)
  181.  
  182.  
  183. // lists/array
  184.  
  185. var myNumbers:[Int] = [] // java: int[] -> swift: [Int]
  186. var numsAgain = [Int]()
  187. var nums3 = Array<Int>()
  188.  
  189. var numsAll0 = [Int](repeating:0, count:20) // makes an array with 20 elements all of them are set to 0
  190.  
  191. var arrWithVals = [1,6,9,123,64] // like new int[] {1,6,9,123,64}  in java
  192.  
  193. print("is myNumbers empty? \(myNumbers.isEmpty)")
  194. myNumbers.append(36)
  195. myNumbers.append(99)
  196. myNumbers.append(14)
  197. myNumbers.append(6)
  198.  
  199. print(myNumbers)
  200.  
  201. print("number of elements in myNumbers \(myNumbers.count)")
  202.  
  203. myNumbers.remove(at: 0) // remove the 0th element (first in the array)
  204. print(myNumbers)
  205.  
  206. // remove by element
  207. let indexToRemove = myNumbers.index(where: { return $0 == 14 })
  208. let indexToRemove2 = myNumbers.index(where: { elem in
  209.     return elem == 14
  210. })
  211. if indexToRemove != nil {
  212.     myNumbers.remove(at: indexToRemove!)
  213. }
  214. print(myNumbers)
  215.  
  216. myNumbers[0] = 9
  217.  
  218. myNumbers.insert(102, at: 1) // insert a new element at a specific index
  219.  
  220. print(myNumbers)
  221.  
  222.  
  223.  
  224. // dictionary (like map in java)
  225. var myDictionary:[String:Character] = [:] // an empty dictionary the keys of type String and values of type Character
  226. var myDictionary2 = [String:Character]()
  227. var myDictionary3 = Dictionary<String, Character>()
  228.  
  229. var dictWithVals:[String:Character] = ["key 1":"1", "key 2":"2", "key 3":"3"]
  230.  
  231. print("elements in dictWithVals \(dictWithVals.count)")
  232.  
  233. print("is myDictionary empty? \(myDictionary.isEmpty)")
  234.  
  235. print(dictWithVals)
  236. dictWithVals["hello"] = "h" // inserting a new entery
  237. dictWithVals["key 1"] = "0" // updating an existing entry
  238. print(dictWithVals)
  239. dictWithVals["key 2"] = nil // removing an entry
  240.  
  241. print(dictWithVals["nonsense"]) // the value of an entry by a key that does not exist is nil
  242.  
  243. print(dictWithVals)
  244.  
  245.  
  246. // set
  247. var mySet = Set<String>()
  248.  
  249. mySet.insert("hello")
  250. mySet.insert("hello1")
  251. mySet.insert("hello2")
  252. mySet.insert("hello") // will not be inserted since we already have "hello"
  253.  
  254. print(mySet)
  255.  
  256. print("number of elements in the set: \(mySet.count)")
  257. print("set contains hello?: \(mySet.contains("hello"))")
  258.  
  259.  
  260. // function
  261.  
  262. func addNumbers(a:Int, b:Int)->Int{
  263.     return a + b
  264. }
  265.  
  266. addNumbers(a: 3, b: 5)
  267.  
  268. func greetName(name:String){
  269.     print("hello there \(name)")
  270. }
  271.  
  272. greetName(name: "Mor")
  273.  
  274. func subNumbers(a:Int = 0, b:Int = 0)->Int{ // default values for a and b
  275.     return a - b
  276. }
  277.  
  278. subNumbers(a:89)
  279.  
  280. func greet(nameToGreet name:String){
  281.     print("hello there \(name)")
  282. }
  283.  
  284. greet(nameToGreet: "Daniel")
  285.  
  286. func sumToNum(_ num:Int)->Int{
  287.     var sum = 0
  288.     for elem in 0...num {
  289.         sum += elem
  290.     }
  291.    
  292.     return sum
  293. }
  294.  
  295. sumToNum(6)
  296.  
  297. func getNumbersAsTuple(num1: Int, num2:Int)->(a:Int, b:Int){
  298.     return (a:num1,b:num2)
  299. }
  300.  
  301. let myNumsAsTup = getNumbersAsTuple(num1: 1, num2: 2)
  302. print("a: \(myNumsAsTup.a), b: \(myNumsAsTup.b)")
  303.  
  304. let myFuncVar = getNumbersAsTuple
  305.  
  306. let myFuncVar2:(String,String)->(Int) = { st,st2 in
  307.     return st.count + st2.count
  308. }
  309.  
  310. let myFuncVar3:(String,String)->(Int) = {
  311.     return $0.count + $1.count // $0 is the first argument, $1 is the second argument
  312. }
  313.  
  314. print(myFuncVar(96, 5))
  315. print(myFuncVar2("hello there","how are you"))
  316.  
  317.  
  318. func doMath(num1:Int, num2:Int, action:(Int,Int)->Int) -> Int{ // this function gets a function as an argument. the function is gets has two arguments - Int and Int- and it returns an Int
  319.     return action(num1, num2)
  320. }
  321.  
  322. let resPlus = doMath(num1: 3, num2: 9, action: { num1, num2 in
  323.     return num1 + num2
  324. })
  325.  
  326. let resStangeMath = doMath(num1: 3, num2: 9, action: {
  327.     return ($0 * $1) % 2
  328. })
  329.  
  330.  
  331. print(resPlus)
  332. print(resStangeMath)
  333.  
  334.  
  335. func makeMultFunc(multiplier:Int) -> (Int)->Int { // functio that returns a function (the function that is returns gets an Int as an argument and returns an Int)
  336.     return { num in
  337.         return multiplier * num
  338.     }
  339. }
  340.  
  341.  
  342. let mult2Func = makeMultFunc(multiplier: 2) // this is a function
  343. mult2Func(5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement