9 Notes August 2021

1. Delete local branch without delete remote branch(git)

- Right click in target branch you want to delete ex: bugs/SD-1986 
- checklist "Force delete" to delete it
- dont checklist "Delete remote branch" it will be delete your remote branch on github

note: If not available in your remote github / still in your local





2. Array feature with condition for get first item

If you want to get first array with condition by score check this example


struct Student {
    let name: String
    let score: Int

}

var students = [
    Student(name: "John", score: 79),
    Student(name: "Bob", score: 44),
    Student(name: "Alice", score: 0),
    Student(name: "Julie", score: 56),
    Student(name: "Patrick", score: 61)
]

// Example 1
let firstStudent = students.first(where: { $0.score < 50 })
print(firstStudent?.name) // Output: Optional("Bob")
let lastStudent = students.last(where: { $0.score == 56 }) print(lastStudent?.name) // Output: Julie


3. When should to use ".map" and ".compactMap"

- Use for one line data, if data model have optional condition
you can use compactMap take a look this code.


let scores = students.map { $0.score }
print(scores)

// OR

struct {
    let str: String?
    let int: Int
}

var data: [Model] = [Model(str: "abc", int: 2), Model(str: "asd", int: 1)]
var scores: [Int] = []

data.forEach { value in
    let strLoop = value.str
    let intLoop = value.int
    //normal use
    score.append(strLoop)
}

// use map
score = data.map {$0.int} // [2, 1]

// use compactMap if data optional
score = data.compactMap {$0.str} // [abc, asd]

- It can use when multi looping array

var data: [Model] = [Model(str: "abc", int: 2), Model(str: "asd", int: 1)]
var data2: [Int ] = [1]

var scores: [Model] = []
data.forEach { value in     score.append(contentOf: data.filter({ return $0.int == value) } // OR
var result: [String] = [] borrowToolId.forEach { id in result.append(contentsOf: toolList.map { if $0.id == id { return $0.name } return "" }) } print(result.filter({$0 != ""})) // ["A", "c"]


4. Sorting with condition use (.map)

This example when condition sorting user by score high to low, for example data you can get in number two.
// sort student by score
let sortedArray = students.sorted(by: { $0.score > $1.score })

// map result into list of names
print(
    sortedArray.map { $0.name }, // ["John", "Patrick", "Julie", "Bob", "Alice"]
    sortedArray.map { $0.score } // [79, 61, 56, 44, 0]
)

5. Getting Highest and Lowest data array

In array can filter what you want this example you want to get hight and
low score (Int) in array models.
// Top score
let topScoreStudent = students.max(by: { $0.score < $1.score })
print(topScoreStudent?.name)


// Lowest Score
let lowestStudent = students.min(by: { $0.score < $1.score })
print(lowestStudent?.name)


6.  How to use single responsibility principle

This example how to use it
// Array get form tenary
var dataA = result.arrayValue.compactMap { models(data: $0) }
response["data"].forEach { (_, json) in
    for (key, item) in result.enumerated() {
        if item.1["id"].stringValue == json["id"].stringValue {
            dataA[key].status = json["data"]["status"].boolValue
        }
    }
    
}
self.dataB = dataA
================================================================================
// Should change to this response["data"].arrayValue.forEach { (json) in for index in 0..<(self?.dataB.count ?? 0) { if self?.dataB[index].symbol == json["id"].stringValue { self?.dataB[index].status = json["data"]["status"].boolValue } } }


7.  Cannot pod Install in terminal macbook (M1)

First setup pod in terminal in macbook air M1 I've get troble cannot running syntac
"pod install" but can run this "arch -x86_64 pod install" if still install i'll get this error.

With a condition:
- macOS Big Sur version 11,2
- MacBook Air (M1, 2020)
- pod version is 1.10.1



For fixing this error you can checklist in "Open using Rosetta"
right click in Application terminal > Get info -> Open using Rosetta
like this images below hope help you.




8.  Manage UserDefault With Enum

I found a example how to manage user default in singelton make it easy to manage fox the major problem about key in userdefault.

// CustomUserDefaults.swift (full)
import Foundation

class CustomUserDefaults {
    // define all keys needed
    enum DefaultsKey: String, CaseIterable {
        case name
        case email
        case isUserLogin
        case userLevel
    }
    static let shared = CustomUserDefaults()
    private let defaults = UserDefaults.standard

    init() {}
    // to set value using pre-defined key
    func set(_ value: Any?, key: DefaultsKey) {
        defaults.setValue(value, forKey: key.rawValue)
    }
    // get value using pre-defined key
    func get(key: DefaultsKey) -> Any? {
        return defaults.value(forKey: key.rawValue)
    }
    // check value if exist or nil
    func hasValue(key: DefaultsKey) -> Bool {
        return defaults.value(forKey: key.rawValue) != nil
    }
    // remove all stored values
    func removeAll() {
        for key in DefaultsKey.allCases {
            defaults.removeObject(forKey: key.rawValue)
        }
    }
}

/* How to use
 
 let name = "jhon"
 CustomUserDefaults.shared.set("data", key: .name)

 */
you can see this explanation of  CustomUserDefaults
source: https://brontoxx.medium.com/manage-userdefaults-keys-with-enum-d9766f6cf288


9.  Getting error after changing project folder name in XCode

For fixing this error you can change in here image below or you can delete ".xcworkspace" and reintall pod "pod install"


enter image description here


No comments: