Tag: iOS

  • Introduction to Table

    Introduction to Table

    Last month I made the Table library. I inspired by javascript console.table.

     

    What is the Table?

    The Table is a helper function to print the tabulation data bypassing the Any data! [e.g., 1d array, 2d array, and dictionary]. I’m sure if you practice coding interviews, it helps you a lot. You don’t need to struggle for checking results using a build-in print function! 

     

    Examples

    The Table can print the tabulation data. It also supports the iPad playground.

    print(
        table: ["Good", "Very Good", "Happy", "Cool!"], 
        header: ["Wed", "Thu", "Fri", "Sat"]
    )
    
    //Result
    +----+---------+-----+-----+
    |Wed |Thu      |Fri  |Sat  |
    +----+---------+-----+-----+
    |Good|Very Good|Happy|Cool!|
    +----+---------+-----+-----+
    
    print(
        table: [
            "1": 1, 
            2: "Hellow?", 
            1.2: 0, 
            "I'm Table": [1, 2, 3, 2, 1]], 
        header: [
            "key", "value"
        ]
    )
    
    //Result
    +---------+---------------+
    |key      |value          |
    +---------+---------------+
    |2        |Hellow?        |
    +---------+---------------+
    |I'm Table|[1, 2, 3, 2, 1]|
    +---------+---------------+
    |1.2      |0              |
    +---------+---------------+
    |1        |1              |
    +---------+---------------+
    
    print(table: [
        [1, 2, 3], 
        [4, 5, 6], 
        [7, 8, 9, 10]
    ])
    
    //Result
    +-+-+-+--+
    |1|2|3|  |
    +-+-+-+--+
    |4|5|6|  |
    +-+-+-+--+
    |7|8|9|10|
    +-+-+-+--+
    

    iPad.PNG

     

    Inside the Table Library

    The declaration of function is similar to standard Swift print function.

    //Standard print
    func print(
        _ items: Any..., 
        separator: String = " ", 
        terminator: String = "\n"
    )
    
    //Table print
    @discardableResult func print(
        table data: Any,
        header: [String]? = nil,
        distribution: TableSpacing = .fillProportionally,
        terminator: String = ""
    ) -> String
    

    The difference is that it is not a variadic function. It take the one data type and then print the tabulation of given data.

     

    How to check the given data type?

    It use the Mirror to check the given data type. It is useful to check the type of any data.

    A representation of the substructure and display style of an instance of any type.

    https://developer.apple.com/documentation/swift/mirror
    let mirrorObj = Mirror(reflecting: data)
    
    //Check one dimensional array
    if mirrorObj == [Any].self {
    }
    //Check two dimensional array
    else if mirrorObj == [[Any]].self {
    }
    //Check Dictionary
    else if mirrorObj == [AnyHashable: Any].self {
    }
    

     

    Check the Item Width

    To display the tabulation of data, It needed item width in data elements. The table cell’s width is set by the longest item width.

    private func tableInfo<Item: LosslessStringConvertible>(
    data: [Item]) -> (
        numberOfItem: Int,
        maxWidth: Int,
        widthInfo: [Int: Int]
        ) {
        let stringData = data.map { String($0) }
        let maxWidth = stringData.sorted { 
            $0.count > $1.count 
        }.first!.count
        var maxWidthDict: [Int: Int] = [:]
        for (index, item) in stringData.enumerated() {
            maxWidthDict[index] = item.count
        }
        return (
            numberOfItem: stringData.count, 
            maxWidth: maxWidth, 
            widthInfo: maxWidthDict
        )
    }
    

    The tableInfo function return the informations of data. I use the LosslessStringConvertible protocols to get the item width by checking the characters of string.

    For example, the integer value 1050 can be represented in its entirety as the string “1050”.

    https://developer.apple.com/documentation/swift/losslessstringconvertible

    This function didn’t considering the Unicode block so far. If you set the CJK(Chinese, Japanese, and Korean) characters then table layout will be broken. I’m going to solve it by using Unocode-Box-Drawing next time.

     

    Unit Test

    Apple tests the print function using TextOutputStream.

    //Declaration of print function by Apple
    func print<Target>(
        _ items: Any..., 
        separator: String = " ", 
        terminator: String = "\n", 
        to output: inout Target
    ) where Target : TextOutputStream
    

    The TextOutputStream is a protocol. The String type already conforms to TextOutputStream. So If you pass the reference of String at to in print function, The output of print will be written into String.

    //https://github.com/apple/swift/blob/master/test/stdlib/Print.swift
    PrintTests.test("StdoutUTF8") {
      expectPrinted("µ", "\u{00B5}")
    }
    
    PrintTests.test("Varargs") {
      var s0 = ""
      print("", 1, 2, 3, 4, "", separator: "|", to: &s0)
      expectEqual("|1|2|3|4|\n", s0)
    
      var s1 = ""
      print(1, 2, 3, separator: "\n", terminator: "===", to: &s1)
      expectEqual("1\n2\n3===", s1)
    
      var s2 = ""
      print(4, 5, 6, separator: "\n", to: &s2)
      expectEqual("4\n5\n6\n", s2)
    
      var s3 = ""
      print("", 1, 2, 3, 4, "", separator: "|", to: &s3)
      expectEqual("|1|2|3|4|\n", s3)
    }
    

    I wrote the unit tests code by checking the result of function.

    func test_1DArray_Of_String_with_header() {
      let output = print(
      table: ["Good", "Very Good", "Happy", "Cool!"],
      header: ["Wed", "Thu", "Fri", "Sat"]
      )
      let expected = """
      +----+---------+-----+-----+
      |Wed |Thu      |Fri  |Sat  |
      +----+---------+-----+-----+
      |Good|Very Good|Happy|Cool!|
      +----+---------+-----+-----+
    
      """
      XCTAssertEqual(output, expected)
    }
    
    func test_2DArray_Of_Int_With_Different_Columns() {
        let output = print(
          table: [
            [1, 2, 3], 
            [4, 5, 6], 
            [7, 8, 9, 10]
          ]
        )
      let expected = """
      +-+-+-+--+
      |1|2|3|  |
      +-+-+-+--+
      |4|5|6|  |
      +-+-+-+--+
      |7|8|9|10|
      +-+-+-+--+
    
      """
      XCTAssertEqual(output, expected)
    }
    

    Swift Over Coffee S2E4: Erica vs the World

    Paul Hudson(HackingWithSwift.com) introduces the Table library on the Swift Over Coffee PodCast Episode S2E4.

    In this episode: WWDC goes WFH, Swift gets some inspiration from JavaScript, and we review your awesome Breathe app submissions.

     

    What’s the next step?

    I’m going to support more types!

    • tuple

    • decodable / encodable

    • custom data type

    • emoji / unicode

  • What’s new on scrollView?

    What’s new on scrollView?

    In Xcode 11, the scroll view has two new things, which are the Content Layout Guide and Frame Layout Guide.

    It’s a very convenient way to set content size for scrollView.

    Let’s check how to use it on the storyboard.

    scrollView.png

    What is the Content Layout Guide?

    It is the size of the content. For example, if your scrollView is enabled vertical scrolling only, then set the subviews constraints relative to the Content Layout Guide.

    viewConstraintStep1.png

    viewConstraintStep2.png

    What is the Frame Layout Guide?

    It is a fixed size of the content. For example, if scrollView is enabled vertical only, then just set the Frame Layout Guide’s width constraint and leave your height constraint.

    viewConstraintStep3.png

    How to resolve the constraint warnings?

    The above steps is an essential for scrollView with its subView. However Storyboard may still complain.

    constraintProblem.png

    To solve the constraint issue, change the intrinsic size of the scroll views subView.

    constraintSolve.png

    Add stackView

    For scrolling the contents, I added stackView with listViews.

    scrolling.gif

    Thanks for reviewing my post

    Shai Mishali

    Navati is having tea

    Bart Pang

  • How to render xib on Storyboard?

    How to render xib on Storyboard?

    When you create the custom view with xib and then set the custom view on Storyboard but if It has not appeared. How can you solve the rendering issue?

    I stuck in similar issues on Xcode 11.

    xcode 11 said -> Failed to render and update auto layout the agent threw an exception

    Here is my solution and I hope it helps you!

    customView.png

    import UIKit
    
    @IBDesignable
    class XibView: UIView {
        let className = String(describing: XibView.self)
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setupNib()
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupNib()
        }
    
        private func setupNib() {
            guard let nib = loadNib() else { return }   
            nib.translatesAutoresizingMaskIntoConstraints = false
            addSubview(nib)
            NSLayoutConstraint.activate([
                nib.leadingAnchor.constraint(equalTo: self.leadingAnchor),
                nib.trailingAnchor.constraint(equalTo: self.trailingAnchor),
                nib.topAnchor.constraint(equalTo: self.topAnchor),
                nib.bottomAnchor.constraint(equalTo: self.bottomAnchor)
            ])
        }
    
        func loadNib() -> UIView? {
            let bundle = Bundle(for: Self.self)
            return bundle.loadNibNamed(String(describing: Self.self), owner: self, options: nil)?.first as? UIView
        }
    }

    image-asset.png

  • How to enable syntax highlighting for Swift on Squarespace

    How to enable syntax highlighting for Swift on Squarespace

    Let’s enabling syntax highlighting for Swift

    The Squarespace supports syntax highlighting for HTML, CSS, and Javascript.

    But It does not support other programming languages.

    To enable it, We can choose the syntax highlighting plugins.

    I recommend PrismJS

    Download PrismJS css and javascript

    prismjs_compressionLevel.png

    Select PrismJS option before downloading it.

    • Compression level to Minified version

    • Language for Swift

    • Plugins (e.g., line numbers)

    prismjs_download.png

    Download the JS and CSS. That’s it.

    Copy and Paste it into the Squarespace

    EditingBlog.png

    Go to the setting Pages > Select your blog page (e.g., Posts)

    CodeInjection.png

    Go to Advanced tap and Copy and Paste the CSS and Javascript code into the Post Blog Item Code injection

    <style>
    <!-- Paste Your PrismJS CSS -->
    </style>
    <script>
    /*
    Paste your PrismJS Javascript
    */
    </script>

    Now We can syntax highlighting for Swift using Markdown

    markdown.png.jpeg

    let greeting = "Welcome to Shawn Baek's blog!"
    print(greeting)