Home Things should Know before start on Artificial intelligence
Post
Cancel
Things should Know before start on Artificial intelligence
Posted Nov 15, 2023
2 min read
What is AI?
Optional is one of the fundamental safety features provided in Swift. It is a container for a value of a particular type. We are using the term container here because it means it may contain a value or not. Nil coalescing
1
??
is an operator used to provide a default if the optional is empty.
In this case, if the name is not available then “name is NA” will be printed. In Swift, we need to always take care while unwrapping an Optional as it might crash the application. The Nil coalescing
1
??
operator does the Job for you if it finds the optional has no value then it uses a default instead.
Do’s and Don’t with
1
??
(#My Opinion)
Following are some of the uses I have seen in the code and we go through them one by one and discuss the case:
(i) Requirement is if Name is not present then display “NA”
(ii) Requirement is to get number of rows in the selected section
funcindexPathOfTableView(){varselectedIndexPath:IndexPath?//Assing a value in code somewhereselectedIndexPath=IndexPath(section:1,row:0)//Uses of the indexPathtableView?.numberOfRows(inSection:selectedIndexPath?.section??0)}
(iii) Requirement is to fetch a random student from the list
funcrandomStudent(){varrandomStudent:Student?//Assign Value to the random student in code//Somewhere in codeletselectedStudent=randomStudent??Student()ifselectedStudent.name.count>0{}}
(i) Do - It is correct usage as we provide the default value if it does not exist.
(ii) Don’t - 0 is not the default value for the section and it also can cause an unexpected issue If the index path in any case nil.
(ii) Don’t - In this case, a student object without referring to any student is not a correct usage it is not a default value. It can cause an issue or crash if you are expecting a real object and get this value.
(iv) Don’t - The requirement is to fetch all names of a student and in case the student does not exist in the record then you should not assign a default value like “”. Either you have some agreed default value or raise an exception name not exist.
(v) Don’t - The requirement is to check if the student list exists or not. In the case of the,
1
if students?.count ?? 0 > 0
condition using the default value is reducing the condition. However, in my opinion, it reduces the readability.
Comments powered by Disqus.