Personal summary about swift

  • 2020-05-14 05:02:22
  • OfStack

Writing in the front

I have been in touch with swift for some time. During this time, I have contacted and learned from other people's experience, and recorded some tips on swift. Although it is not a profound principle knowledge, it can be used in ordinary projects to improve the development efficiency

The & # 128579; Haha, here is a simple summary:

Enumeration (ENUM)

Combine 1 small scenario, for example, we will make a small case about gender judgment:
Maybe that's the first thing that comes to mind, hard coded write, manual input every time


var gender = ""
gender = "man"
switch gender {
case "man":
  print("man")
  case "female":
  print("female")
default:
  print("other")
}

But if we write it using enumeration:


enum Gender {
  case man
  case female
  case other
}
var gType: Gender = .man
switch gType {
case .man:
  print(" men ")
case .female:
  print(" women ")
case .other:
  print(" Other types of ")
default:
  print(" I don't know ")
}

Writing the required type into enum reduces the chance of accidental typing errors, and the editor will point out instances that are not in the scope of enum.

Null conjunction operator

For example, if we want to define the default text for some label, that is, if we don't set it manually, the label will be displayed with the default text. We might say something like this:


var customText: String?
var defaultText = " How do you do "
var textToUse = ""
if let text = customText {
  textToUse = text
} else {
  textToUse = defaultText
}

If I were to write it this way it would look something like this:


var customText: String?
var defaultText = " How do you do "
var textToUse = ""
var textToUse = customText ?? defaultText

The & # 63; The & # 63; defaultText if textToUse is nil or customText if textToUse is nil

functional

For example, if we get an odd number within 10, the first idea is to use for loop:


var arr = [Int]()
for i in 1...10 {
  if i % 2 == 1 {
    arr.append(i)
  }
}
print(arr)

Of course, you can calculate the result. If you think of it another way, swift has built-in filter function:


var arr = (1...10).filter { (num) -> Bool in
  num % 2 == 1
}
print(arr)

Closure \ function

For example, two strings are concatenated

Use function:


func sum(a: String, b: String) -> String {
  return a + b
}
var result = sum(a: " hello ", b:" Ha, ha, ha ")

If you use closures:


var sumStringClosure: (String, String) -> String = {
  $0 + $1
}
sumStringClosure("hello", "world")

There is no feeling easy a lot

convenience init for easy initialization

We declare a class, set a variable to that class and initialize it


class Animal {
  var dog: Int?
  var cat: Int?
  init(dog: Int, cat: Int) {
    self.dog = dog
    self.cat = dog
  }
}
var daDi = Animal(dag: 2, cat: 4)
daDi.dog
daDi.cat

If we want to set the number of dog and cat in this class every time we use the Animal class, we can use convenience init


class Animal {
  var dog: Int?
  var cat: Int?
  init(dog: Int, cat: Int) {
    self.dog = dog
    self.cat = dog
  }
  convenience init() {
    self.init(dog: 10, cat: 10)
  }
}

var daDi = Animal()
daDi.dog
daDi.cat

Attribute to observe

Since swift was updated to swift3, we found that the set\get method of the variable has been changed. A convenient property has been added, which is willSet and didSet. For example, if we want to find the circumference of a square, function looks like this:


enum Gender {
  case man
  case female
  case other
}
var gType: Gender = .man
switch gType {
case .man:
  print(" men ")
case .female:
  print(" women ")
case .other:
  print(" Other types of ")
default:
  print(" I don't know ")
}
0

If we use the variable's property observation method:


enum Gender {
  case man
  case female
  case other
}
var gType: Gender = .man
switch gType {
case .man:
  print(" men ")
case .female:
  print(" women ")
case .other:
  print(" Other types of ")
default:
  print(" I don't know ")
}
1

willSet
Is called before the property changes
didSet
Is called after the property has changed.

Traversal methods

Print string: if using while


enum Gender {
  case man
  case female
  case other
}
var gType: Gender = .man
switch gType {
case .man:
  print(" men ")
case .female:
  print(" women ")
case .other:
  print(" Other types of ")
default:
  print(" I don't know ")
}
2

We have to define a variable to ensure that the number of times we print is up to our requirements, but the more variables we define, the greater the risk of error, so we should write as little code as possible and change to for loop version:


for _ in 1...10 {
  print("itembeu")
}

There is no need to define redundant variables, because the swift syntax is designed to use _ instead of variables that can be ignored

Calculate the property \ function

Take the diameter and radius of the circle:
1. Using the function: in this case, we need to write two function to find the diameter according to the radius and the radius according to the diameter


enum Gender {
  case man
  case female
  case other
}
var gType: Gender = .man
switch gType {
case .man:
  print(" men ")
case .female:
  print(" women ")
case .other:
  print(" Other types of ")
default:
  print(" I don't know ")
}
4

2. Use the calculated properties of variables


enum Gender {
  case man
  case female
  case other
}
var gType: Gender = .man
switch gType {
case .man:
  print(" men ")
case .female:
  print(" women ")
case .other:
  print(" Other types of ")
default:
  print(" I don't know ")
}
5

We know that the diameter and the radius are dependent on each other, and it looks a lot simpler to use the properties of the variables than to use the functions.

The generic

If we need to print out variables from arrays of different types, we might do this:


enum Gender {
  case man
  case female
  case other
}
var gType: Gender = .man
switch gType {
case .man:
  print(" men ")
case .female:
  print(" women ")
case .other:
  print(" Other types of ")
default:
  print(" I don't know ")
}
6

We need to define different types of arrays, and if there are more types, we will do a little more useless work. In this case, we will use generics to solve this problem:


enum Gender {
  case man
  case female
  case other
}
var gType: Gender = .man
switch gType {
case .man:
  print(" men ")
case .female:
  print(" women ")
case .other:
  print(" Other types of ")
default:
  print(" I don't know ")
}
7

Generics are at the heart of the powerful Swift language. Generics are an abstraction of types that allow developers to express the intent of their code in a more flexible and convenient way. Has reference function parameter must have a clear argument types, sometimes developers will encounter this kind of situation, as we take the example above, due to the variable has a type, realize the same function, may need to override into multiple function to realize, this greatly wasted development costs, use generics, can perfectly solve the problem.

expand

swift doesn't have category in OC, but it does have extension, so we're dealing with extension a lot, and if we want to square a number, we can declare a function, like this:


func squ(x: Int) -> Int {
  return x * x
}
var s = squ(x: 10)

So if we want to take 10 to the fourth, we have var s = squ(x: 10)
squ(x: s) creates redundant variables.
Usage extension:


enum Gender {
  case man
  case female
  case other
}
var gType: Gender = .man
switch gType {
case .man:
  print(" men ")
case .female:
  print(" women ")
case .other:
  print(" Other types of ")
default:
  print(" I don't know ")
}
9

Simple, no need to create more variables.

Gaurd let \ if let

Verify username and password:

1. To use if let, we need 1 layer of nesting


var uName: Double?
var uPassword: Double?
func userLogIn() {
  if let username = uName {
    if let password = uPassword {
      print(" welcome , \(username)"!)
    }
  }
}

2, use gaurd let, if uName or uPassword is nil, the program will go return method, early end of the run, otherwise print(" welcome, \(username)!" )


var uName: Double?
var uPassword: Double?
func userLogIn() {
   guard let username = uName, let password = uPassword 
     else { return } 
    print(" welcome , \(username)!") 
}


Related articles: