当前位置:网站首页>Technology sharing swift defense programming
Technology sharing swift defense programming
2022-07-05 03:28:00 【Julie^_^ JuneLee】
1、 background
For developers to write code more effectively , Probability of preventing errors , We are in the process of code design and writing , Try to make sure your code doesn't make mistakes , Defensive programming enables us to find small problems as soon as possible , Instead of waiting until customers give feedback or receive abnormal crashes ?
As a developer , Few people can swear that their programs are 100% non bug, So moderate defense will improve development quality and reduce debugging bug Time for
An effective way to defend against coding :
- Once you encounter an agreed exception , The program must be compatible , You must not let the program Crash
- Once you encounter a predetermined exception , Just run out , If the upper layer does not deal with , be Crash
2、 Defensive programming habits
- 1.
If not necessary , Don't add entities or classes
: If you can do the same thing with fewer things , Then add more variables or entities 、 You need energy to maintain , It's also more likely to go wrong - 2.
Don't rush to write code
: Every line of code you start writing needs to think twice , Consider what kind of mistakes may occur , Consider all possible situations - 3.
Dispose of compilation warnings as much as possible
: Handling compilation warnings is a good habit , Compilation warnings may hide certain errors - 4.
Check all return values
: Check the return value of the method or property , Prevent exceptions - 5.
Use cast cautiously
: Cast needs to consider the input parameter type , Handle with care , Explain the coercion as clearly as possible - 6.
Check the boundary of the value
: For the value 、 The range of the array should be judged , Many lessons of historical collapse are caused by crossing the border
3、Swift Some points needing attention in
3.1、 optional type (Optional Type)
- Try to avoid declaring implicitly optional types , Unless it can be determined that it must have value when used
- Avoid using
as!
ortry!
Equal coercion , Use!
If abnormal, it will definitely lead to Crash - Be careful to use forced unpacking for optional variables , Optional default values can be used
The value of an optional variable , May be nil, If forced unpacking is used for optional variables , The context needs to be clear , Otherwise, there may be Crash
var test: String?
print(test) //nil
print(test!) //error、Crash
Better use , Use money to judge or use let Variable
if test != nil {
}
if let tempTest = test {
}
3.2 When multiple operators are combined , Use parentheses to prioritize
let flag = true || false && false
let flag1 = (true || false) && false
let flag2 = true || (false && false)
Print the results
flag = true
flag1 = false
flag2 = true
first line : The naked eye can't see who has a high level of operation
The second line : hold || Operations are enclosed in parentheses , Higher priority
The third line : hold && Operations are enclosed in parentheses , Higher priority
According to the printing results ,&& The priority ratio || high
3.3 Call in closure self Avoid circular references
Closures are commonly used , Will be [weak self] Put it in front of the closure parameter
testBlock() {
[weak self] name in
self?.doSomething()
}
4、swift Some specifications in
1. Use as much as possible
let
, Be able to use let You don't have to var2. When declaring class methods and properties , priority of use
static
Instead ofclass
3. If the function has no arguments , The function body is simple , Only some objects or values are fed back , It is recommended to use calculated properties
struct Square { var side: CGFloat = 2.0 // recommend var girth: CGFloat { return side * 4 } // Not recommended // func girth() -> CGFloat { // return side * 4 // } // recommend func halfGirth() -> CGFloat { self.side = side * 0.5 return side * 4 } // Not recommended // var halfGirth: CGFloat { // self.side = side * 0.5 // return side * 4 // }
4. Enumerating using the preferred set switch When the sentence is , Do not include default, conversely ,switch You need to use default Including other situations
5. When expanding optional parameters , Recommended
guard
sentence , instead ofif
sentence , Reduce code nesting or indentation 、 Increase code readability// recommend guard let tempTest = test else { return } doSomething(on: tempTest) // Not recommended if let tempTest = test { doSomething(on: tempTest) } //
边栏推荐
- Jd.com 2: how to prevent oversold in the deduction process of commodity inventory?
- [micro service SCG] 33 usages of filters
- GFS distributed file system
- Port, domain name, protocol.
- 有個疑問 flink sql cdc 的話可以設置並行度麼, 並行度大於1會有順序問題吧?
- [Yu Yue education] National Open University autumn 2018 8109-22t (1) monetary and banking reference questions
- In MySQL Association query, the foreign key is null. What if the data cannot be found?
- Kubernetes - Multi cluster management
- Three line by line explanations of the source code of anchor free series network yolox (a total of ten articles, which are guaranteed to be explained line by line. After reading it, you can change the
- Sqoop installation
猜你喜欢
College Students' innovation project management system
Sqoop安装
IPv6 experiment
[groovy] loop control (number injection function implements loop | times function | upto function | downto function | step function | closure can be written outside as the final parameter)
Basic knowledge of tuples
Pat class a 1160 forever (class B 1104 forever)
腾讯云,实现图片上传
SQL injection exercise -- sqli Labs
Devtools的簡單使用
Yyds dry goods inventory embedded matrix
随机推荐
Kubernetes -- cluster expansion principle
Design and implementation of community hospital information system
[Yu Yue education] National Open University autumn 2018 8109-22t (1) monetary and banking reference questions
SFTP cannot connect to the server # yyds dry goods inventory #
Flume configuration 4 - customize mysqlsource
Zero foundation uses paddlepaddle to build lenet-5 network
返回二叉树中两个节点的最低公共祖先
Idea inheritance relationship
[Chongqing Guangdong education] 2777t green space planning reference questions of National Open University in autumn 2018
Monitoring web performance with performance
Flume配置4——自定义MYSQLSource
The perfect car for successful people: BMW X7! Superior performance, excellent comfort and safety
[200 opencv routines] 99 Modified alpha mean filter
The perfect car for successful people: BMW X7! Superior performance, excellent comfort and safety
NPM introduction link symbolic link
Design and practice of kubernetes cluster and application monitoring scheme
Delphi free memory
Is there any way to change the height of the uinavigationbar in the storyboard without using the UINavigationController?
Use UDP to send a JPEG image, and UPD will convert it into the mat format of OpenCV after receiving it
Basic knowledge of tuples