How to use AS, AS?, AS! in Swift

Swift

Preface

Hello everyone, today we will learn more and more details about the use of operators as, as?, as! in Swift. These operators are also one of the factors that make up security in Swift code. If you understand it well your code will be very safe, otherwise it can cause bugs and crash your application constantly.

To get started in this tutorial you should use Xcode Playground To practice coding according to the examples in this tutorial, it will make it easier for you to understand and remember for longer. In this post there is some knowledge about optional If you do not understand it, you can find out here.

First, we will learn about 2 characters “?”, “!”: In variable declaration, the character “?” That is, we say that the variable is likely to be nil but not always valid. In regular statements, the “?” appears indicating that the variable can be nil and when using that variable the variable is nil then the app will not crash. In variable declaration, when using the character “!” that is, they are extremely sure that the variable has “!” will always be valuable. If there is no value in those variables then using that variable will cause application crash.

Note: When we declare a variable but do not know if this variable has a value, we should use the character “?” And vice versa, if we know the variable always has a value, we will use the character “!”. For example:

var a:Int?

print(a) // Hiện thị giá trị nil. Không carsh


let b:Int!

print(b) // Sẽ bị báo lỗi ngay lập tức.(Bị crash)

//We can edit:

let b:Int! = 1
print(b)

//or

var b:Int!
b = 1
print(b)

As used in case we want to upcasting certain data to the desired data type. Note: When used As You have to make sure that the data type you want to cast is the same as the data type of the variable you are trying to cast, otherwise a bug will occur. For example:

// Ép kiểu (Up casting)
   let button = UIButton()
   let view = button as UIView

// Khái báo biến và ép kiểu
   let string = "3"
   let nsString = string as NSString
   let value = nsString.floatValue // 3

   let rawString: AnyObject = "Tự học Swift"
   let optionalString: AnyObject? = "Tự học Swift"
   let nilString: AnyObject? = (nil as String?)

   let rawInt: AnyObject = Int(3)
   let optionalInt: AnyObject? = Int(3)
   let nilInt: AnyObject? = (nil as Int?)

// Sử dụng as
   let result1 = rawString as String       // AnyObject is not convertible to String
   let result2 = optionalString as String  // AnyObject? is not convertible to String
   let result3 = nilString as String       // AnyObject? is not convertible to String
   let result4 = rawInt as String          // AnyObject is not convertible to String
   let result5 = optionalInt as String     // AnyObject? is not convertible to String
   let result6 = nilInt as String          // AnyObject? is not convertible to String

However, we can use safe casting by using the following operator: As? Used like As But the difference is that if we fail to cast it, it returns value nil. For better understanding see the following example: For example:

   let string = "3"
   let nsString = string as NSString
   let value = nsString.floatValue // 3

   let rawString: AnyObject = "Tự học Swift"
   let optionalString: AnyObject? = "Tự học Swift"
   let nilString: AnyObject? = (nil as String?)

   let rawInt: AnyObject = Int(3)
   let optionalInt: AnyObject? = Int(3)
   let nilInt: AnyObject? = (nil as Int?)

// as?
   let result17 = rawString as? String // String? "Tự học Swift"
   let result18 = optionalString as? String // String? "Tự học Swift"
   let result19 = nilString as? String // String? nil
   let result20 = rawInt as? String // String? nil
   let result21 = optionalInt as? String // String? nil
   let result22 = nilInt as? String // String? nil

   let result23 = rawString as? String! // Không thể ép kiểu từ AnyObject sang kiểu optional String!
   let result24 = rawString as? String? // Không thể ép kiểu từ AnyObject sang kiểu optional String?
   let result25 = optionalString as? String! // String!? "Tự học Swift"
   let result26 = optionalString as? String? // String?? "Tự học Swift
   let result27 = optionalInt as? String? // String?? nil

As! Used in the same way as As however it will force our variable to be cast to some type. If the variable cannot be forced to that type, the application will crash immediately. Note: Using this is very dangerous, if it is not certain that the type we want to force will be successful, it will crash the application. If we feel uncertain or vague about this residual coercion we should use it as? To successfully catch the case of failure and continue handling. For example:

if let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell {
    //Nếu chúng ta ép kiểu thành công thì sử dụng biến cell để làm gì đó
} else {
    // Ép không thành công thì chúng ta xử lý gì đó
}

For example:

   let string = "3"
   let nsString = string as NSString
   let value = nsString.floatValue // 3

   let rawString: AnyObject = "Tự học Swift"
   let optionalString: AnyObject? = "Tự học Swift"
   let nilString: AnyObject? = (nil as String?)

   let rawInt: AnyObject = Int(3)
   let optionalInt: AnyObject? = Int(3)
   let nilInt: AnyObject? = (nil as Int?)

// as!
   let result7 = rawString as! String // String "Tự học Swift"
   let result8 = optionalString as! String // String "Tự học Swift"
//    let result9 = nilString as! String // unexpectedly found nil while unwrapping an Optional value
//    let result10 = rawInt as! String // Could not cast value of type '__NSCFNumber' (0x107c98130) to 'NSString' (0x1082afb00).
//    let result11 = optionalInt as! String // Could not cast value of type '__NSCFNumber' (0x101e95130) to 'NSString' (0x1024acb00).
//    let result12 = nilInt as! String // unexpectedly found nil while unwrapping an Optional value

 //    let result13 = rawString as! String! // Không thể ép kiểu từ AnyObject thành kiểu optional String!
 //    let result14 = rawString as! String? //Không thể ép từ kiểu AnyObject thành kiểu optional  String?
   let result15 = optionalString as! String! // String! "Tự học Swift"
   let result16 = optionalString as! String? // String? "Tự học Swift"

Note:As! It is also not possible to force certain data types to type optional. As? And As! In addition to casting to create a new variable and using it, they can also be used to check if the variable is the exact type of data you want to test. If you successfully pressed the type as? Then it will give you a new variable type optional, opposite to as!, when you successfully cast it will return a normal variable. To understand more we will refer to the example below:

Example 1:

var optionalString = dict.objectForKey (“SomeKey”) as? String

optionalString Will be an optional variable of type String ?, If the case we don’t cast to String, it means there will be some case where the value of dict.objectForKey (“SomeKey”) is a data type. Some other than String is then used as? String will fail to cast, optionalString variable will be interrupted nil.

Example 2:

var optionalString = dict.objectForKey (“SomeKey”) as! String?

In this case, you tell the system that the data type of dict.objectForKey (“SomeKey”) is of type String ?, must be String ?. If your assertion is correct then we will have an optionalString variable of type String? But unfortunately if your assertion is false, which means dict.objectForKey (“SomeKey”) is not a String ?, crash will occur immediately. So the solution here is we will use the syntax if let good guard let… to check the data type of that variable, if we’re not sure. For example:

if let string = dict.objectForKey("SomeKey") as? String { 
  //Sử dụng biến đó
  println(string) 
} else {
  // Làm gì đó nếu biến đó không phải kiểu String
}



Guard let string = dict.objectForKey("SomeKey") as? String else { 
  // Làm gì đó nếu biến đó không phải kiểu String
return
} 
//Sử dụng biến đó
println(string)

The end of this section is not difficult to understand, but if you really do not know and understand the keywords as, as ?, as! then when using it can cause an unreasonable crash of the application. If you are not sure, you should practice the examples above with the background to understand and remember longer the should and should not use the keywords above. Hope you enjoyed and learned a lot from this article. Hope you share it for everyone to learn and exchange together. Any questions or discussions about the article, you can leave a comment below I will support soon.

Thank you very much for watching.

Hope this helps!

Source link

Leave a Reply

Your email address will not be published. Required fields are marked *