Swift: String basics


/ Published in: Objective C
Save to your folder(s)

I've been learning swift lately and here are a few basics.


Copy this code and paste it in your HTML
  1. ////////////////////////////////
  2. //Strings + Error Protection
  3. ////////////////////////////////
  4.  
  5. import UIKit
  6.  
  7. /** ** ** ** ** ** ** ** ** ** **
  8. Types of Strings
  9. ** ** ** ** ** ** ** ** ** ** **/
  10. //Simple String or Non-Optional String
  11. var name:String
  12. name = "Chris"
  13.  
  14. //Optional String
  15. var jobFunction:String?
  16. jobFunction = "Developer"
  17.  
  18. //Implicitely unwrapped Optional String
  19. var jobDept:String!
  20. jobDept = "Dev Team"
  21.  
  22. /** ** ** ** ** ** **
  23. Optional String? Use Cases
  24. ** ** ** ** ** ** **/
  25.  
  26. //A. Print Optional String
  27. if(jobFunction != nil){
  28. //Without Force Unwrapping
  29. println("Access my inner \(jobFunction)")
  30. //With Force Unwraping
  31. println("Access my inner \(jobFunction!) through unwrapping!")
  32. } else {
  33. println("jobFunction is nil")
  34. }
  35.  
  36. //B. Optional-binding Syntax: if true, then assign the value to a CONSTANT
  37. if let jobTitle = jobFunction {
  38. //Since jobFunction exists, the name is assigned to jobTitle
  39. println(jobTitle)
  40. }
  41.  
  42. /** ** ** ** ** ** **
  43. Implicit String! Use Cases
  44. ** ** ** ** ** ** **/
  45.  
  46. //A. Print Implicite String
  47. if jobDept != nil {
  48. println("My department is \(jobDept)")
  49. } else {
  50. println("jobDept is nil")
  51. }
  52.  
  53. //How to protect yourself from force unwrapping a nil value
  54. //B. Nil-coalescing operator: Check variable to see if it's nil. If it's not nil, use that value, otherwise, use something else
  55.  
  56. let finalName = (name ?? "no name")
  57. let finalJob = (jobFunction ?? "no job")

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.