9 NOTES IN JUNE 2020




1. The Power Of Protocol

Using Protocol Extensions for Default Implementations
example protocol with extension

protocol Printer {
    func printMe()
}

extension Printer {
    func printMe() {
        print("Hello junk food")
    }
}
      

use in viewController look like
class ViewController: UIViewController {

    class A: Printer {}
    var a = A()

    override func viewDidLoad() {
        super.viewDidLoad()
        a.printMe() //result -> Hello junk food
} }

Source: https://medium.com/better-programming/6-swifty-ways-of-writing-code-f260286a0dbb

2. Clean Table View


 - Make one class for tableView


import UIKit

typealias MyStringCompletion = (String) -> Void

class StaticViewDataSource: NSObject, UITableViewDelegate, UITableViewDataSource {
    var dataArray: [String]?
    var delegate: MyStringCompletion?

    init(items: [String]) {
        self.dataArray = items
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "staticcell", for: indexPath)
        cell.textLabel?.text = dataArray?[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        delegate?(dataArray?[indexPath.row] ?? "")
    }
}

   

And call table view in viewcontroller

import UIKit

// MARK: parent Class

class CleanTableViewController: UIViewController {
    @IBOutlet var tableView: UITableView!

    var datasource: StaticViewDataSource!
    let arrayString = ["b89", "a131", "5rte", "54gff"]

    override func viewDidLoad() {
        super.viewDidLoad()
        datasource = StaticViewDataSource(items: arrayString)
        tableView.dataSource = datasource
        tableView.delegate = datasource
        datasource.delegate = { str in
            print(str)
        }
    }
}

Source: Medium


3. Permission denied "Brew install xcodegen"

I try to Intall xcodegen in terminal and response like this
'touch: /usr/local/Homebrew/.git/FETCH_HEAD: Permission denied'

so this my solution

- $sudo chown -R $(whoami) /usr/local/Homebrew/
- password:
- $
now type "Brew install xcodegen" again and enter


4. Error install xcodegen in terminal

In another case my install brew error like this below

➜  ios git:(development) brew install xcodegen
Updating Homebrew...
Warning: You are using macOS 10.15.
We do not provide support for this pre-release version.
You will encounter build failures with some formulae.
Please create pull requests instead of asking for help on Homebrew's GitHub,
Discourse, Twitter or IRC. You are responsible for resolving any issues you
experience, as you are running this pre-release version.

==> Downloading https://homebrew.bintray.com/bottles/xcodegen-2.6.0.mojave.bottle.tar.gz
-=O=-                                      #     #     #    #                 
curl: (7) Failed to connect to homebrew.bintray.com port 443: Operation timed out
Error: Failed to download resource "xcodegen"
Download failed: https://homebrew.bintray.com/bottles/xcodegen-2.6.0.mojave.bottle.tar.gz
Warning: Bottle installation failed: building from source.
==> Downloading https://github.com/yonaskolb/XcodeGen/archive/2.6.0.tar.gz
-=O=-          #     #    #     #                                             
curl: (7) Failed to connect to github.com port 443: Operation timed out
Error: An exception occurred within a child process:
  DownloadError: Failed to download resource "xcodegen"
Download failed: https://github.com/yonaskolb/XcodeGen/archive/2.6.0.tar.gz

 And This how I fix it
  - Change network connection from network office to my personal wifi
  - now I can intall xcodegen

 Reason: In my case because my office connection is block github or cannot open github

If succesful look like 

➜  ios git:(development) brew install xcodegen
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 4 taps (homebrew/core, homebrew/cask, dart-lang/dart and peripheryapp/periphery).
==> New Formulae
abseil                               dynet                                killswitch                           postgresql@11
adios2                               earthly                              kind                                 powerline-go
airshare                             elasticsearch@6.8                    komposition                          prestosql
alp                                  emacs-dracula                        krew                                 protobuf@3.7
ansible@2.8                          ensmallen                            kubebuilder                          protoc-gen-grpc-web
apollo-cli                           erlang@22                            kumactl                              prover9
appium                               eureka                               kyma-cli                             psc-package
archiver                             eva                                  lanraragi                            publish
arduino-cli                          faiss        
...


5. Terminal do not show git branch(.oh my zsh)

In case I use .oh my zsh and don't show branch, before that I delete duplicate xcode and open terminal make my zsh not like before
so I try to reinstall .oh my zsh, but not showing git branch, and then I searchong a lot finnaly get solution
- Xcode must be swichting to xcode active

$sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer


6.  Add. Localization file two language in xcode

-  File ->. new file (select in page resource) -> Strings File




Before setting in project



-  go to project setting -> tab info (section localization) 
    add new language


- So in your project folder look like this


After setting in project

Source: https://medium.com/lean-localization/ios-localization-tutorial-938231f9f881


7. Use localization in project

- First step in Localizable.strings write key and value like this  for base language

"mainTitle"                      = "Language";
"about"                          = "About";
"update"                         = "Update";
"dateAndTime"                    = "Date And Time";
"storage"                        = "Storage";       
- Next language use same keys
"mainTitle"                      = "ランゲージ";
"about"                          = "およそ";
"update"                         = "アップデイト";
"dateAndTime"                    = "日時";
"storage"                        = "ストレージ";
- In viewController, you can add all this code

import UIKit

class LanguageHelper {
    static func localize(key: String) -> String {
        return key.localized
    }
}

struct ConstantLang {
    static let language = LanguageHelper.localize(key: "mainTitle")
    static let about = LanguageHelper.localize(key: "about")
}

class LocalizeLocalViewController: UIViewController {
    @IBOutlet weak var mainTitle: UILabel!
    @IBOutlet weak var aboutLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.mainTitle.text = ConstantLang.language
        self.aboutLabel.text = ConstantLang.about
    }
}

extension String {
    //MARK: Localization
    var localized: String {
        return NSLocalizedString(self, comment: "")
    }
}



Now you can change language  in settings on device or simulator 
 -> go Settings -> General -> Language & Region -> iPhone Language 
select language what you set in localization in xcode



8. How to use git add in terminal

Before you add some git check status first ($git status)

- $git add -A   -> stages all changes (git add all file change)
- $git add .    -> stages new files and modifications, without deletions
- $git add -u   -> stages modifications and deletions, without new files
- $git add file/common/file.swift  -> (git just add single file)





9.  Optional protocol 

Problem :

In the condition, I want to use protocol in my viewController but except some func so a lot search 
finally I found solution, create extension from your protocol in end of function give brackets "{}"


Original image

Solution:

import Foundation

public protocol SomeProtocol: class {
    func didInteger(into: Int)
    func didTanDis(str: String)
}
extension SomeProtocol {
func didString(str: String) {} }

This optional  is   func didString(str: String) ,  so you use look like

extension ProtocolViewController: SomeProtocol {
func didInteger(into: Int) {
print("go to "+into.description) } }

Source: https://stackoverflow.com/a/48838620/8366535







 

No comments: