SWIFTip#6: Casual insight of the week
Learning around swift.
Here is a weekly insight to enhance skills of Swift good practice. Do comment if you have the better suggestion for swift learners.
Thank you.
allSatisfy(_:)
Array Instance Method
// The following code uses this method to test whether all
// the scores in an array is greater than 85:let scores = [85, 88, 95, 92]
let passed = scores.allSatisfy { $0 >= 85 }//OUTPUT: passed ==> Truelet names = ["Swift", "Junk", "box"]
let isMoreThanThree = names.allSatisfy({ $0.count >= 3})//OUTPUT: isMoreThanThree ==> true
Difference between map(_:) and compactMap(_:)
// Use compactMap function to receive an array of nonoptional values
// when your transformation produces an optional value.let possibleNumbers = ["1", "2", "three", "///4///", "5", "Fish"]
let mapped: [Int?] = possibleNumbers.map { Int($0) }
// [1, 2, nil, nil, 5, nil]let compactMapped: [Int] = possibleNumbers.compactMap { Int($0) }
// [1, 2, 5]
Which one is better for Constant? Struct or enum
The advantage of using a case-less enumeration is that it can’t accidentally be instantiated and works as a pure namespace.
Easy Keyboard dismiss
Dimiss Keyboard on Drag of any scrolling event
// UITableView
tableView.keyboardDismissMode = .onDrag //.interactive//UICollectionView
CollectionView.keyboardDismissMode = .onDrag//UIScrollView
scrlView.keyboardDismissMode = .onDrag
Tools for iOS Development
- What is Failable Initializers?
An initialization function (“initializer”), can be declared to be optional (
init?
). You mustreturn nil
if the initialization process fails.
- Can I initialise enum? How?
An enumeration (
enum
) does not require an explicit initializer, but enumerations can be extended to have custom initializers.
- is it mandatory to Initialze structure?
A structure (
struct
) is a group of values, so each value must be initialized before the structure can be accessed.