<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Elio Shih on Medium]]></title>
        <description><![CDATA[Stories by Elio Shih on Medium]]></description>
        <link>https://medium.com/@elio0shin?source=rss-a4d0bfa86011------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MGo5YkibNAToCBVJOHKBJQ.jpeg</url>
            <title>Stories by Elio Shih on Medium</title>
            <link>https://medium.com/@elio0shin?source=rss-a4d0bfa86011------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:43:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elio0shin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Protocols & Delegate 閱讀心得筆記]]></title>
            <link>https://medium.com/elio-iosapp/protocols-delegate-%E9%96%B1%E8%AE%80%E5%BF%83%E5%BE%97%E7%AD%86%E8%A8%98-560135a77454?source=rss-a4d0bfa86011------2</link>
            <guid isPermaLink="false">https://medium.com/p/560135a77454</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Elio Shih]]></dc:creator>
            <pubDate>Tue, 07 Dec 2021 17:13:17 GMT</pubDate>
            <atom:updated>2021-12-09T06:24:24.689Z</atom:updated>
            <content:encoded><![CDATA[<h3>Protocols — 協定</h3><blockquote><em>A </em>protocol<em> defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be </em>adopted<em> by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to </em>conform<em> to that protocol. -</em><a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html"><em>The Swift Programming Language Guide by Apple</em></a></blockquote><p>協定 (protocols) 只單純提供定義一個藍圖，規定完成某項任務or功能所需要的方法或屬性。</p><p>Classes和structs提供物件的資訊，協定則提供物件將會執行的動作。而協定是抽象的，可以使用協定替程式碼抽象化。</p><h3>Syntax</h3><blockquote><em>class 名稱: 父類別, 協定Ａ, 協定 B</em></blockquote><pre>class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {<br>    // class definition goes here<br>}</pre><h3>Property Requirements</h3><blockquote><em>If a protocol requires a property to be gettable and settable, that property requirement can’t be fulfilled by a constant stored property or a read-only computed property. If the protocol only requires a property to be gettable, the requirement can be satisfied by any kind of property… -</em><a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html"><em>The Swift Programming Language Guide by Apple</em></a></blockquote><p>Protocols 無法定義屬性為儲存or計算屬性，只定義屬性的名稱、是否為 實體屬性 或為 型別屬性 。並且可以定義屬性是否為唯獨( { get } )或可讀寫( {get set} )的。</p><pre>//型別屬性<br>protocol SomeProtocol {<br>  static var mustBeSettable: Int { get set }<br>  static var doesNotNeedToBeSettable: Int { get }<br>}</pre><pre>//實例屬性<br>protocol FullyNamed {<br>    var fullName: String { get }<br>}</pre><pre>class User: FullyNamed {<br>    var firstName: String?<br>    var lastName: String<br>    init(lastName: String, firstName: String? = nil) {</pre><pre>        self.firstName = firstName<br>        self.lastName = lastName</pre><pre>    }<br>    var fullName: String {<br>        return (firstName != nil ? firstName! + &quot; &quot; : &quot;&quot;) + lastName<br>    }<br>}</pre><pre>var user = User(lastName: &quot;Shin&quot;, firstName: &quot;Elio&quot;)</pre><pre>print(user.fullName)</pre><pre>// Elio Shin&quot;</pre><h3>Method Requirements</h3><p>定義實體方法或型別方法，並不進行實作，實作是交由給遵循此Protocol的型別來做</p><blockquote><em>可以定義有可變數量的參數 (variadic parameter) 的方法。 不可為方法的參數提供預設值 加上 </em><em>static 關鍵字，就會使它成為是屬於那個型別本身的方法。</em></blockquote><pre>protocol SomeProtocol {<br>    static func someTypeMethod()<br>}</pre><pre>protocol RandomNumberGenerator {<br>    func random() -&gt; Double<br>}</pre><pre>class LinearCongruentialGenerator: RandomNumberGenerator {<br>    var lastRandom = 42.0<br>    let m = 139968.0<br>    let a = 3877.0<br>    let c = 29573.0<br>    func random() -&gt; Double {<br>        lastRandom = ((lastRandom * a + c)<br>            .truncatingRemainder(dividingBy:m))<br>        return lastRandom / m<br>    }<br>}<br>let generator = LinearCongruentialGenerator()<br>print(&quot;Here&#39;s a random number: \\(generator.random())&quot;)<br>// Prints &quot;Here&#39;s a random number: 0.3746499199817101&quot;<br>print(&quot;And another one: \\(generator.random())&quot;)<br>// Prints &quot;And another one: 0.729023776863283&quot;</pre><h3>Self ? self?</h3><p>self通常是指class 或 struct 中的當前對象，Self表示任何當前的類別。</p><p>在 protocol 裡 Self 不僅指的是 實現該協議的型別本身，也包括了這個型別的子類</p><p>Protocol 自身不是一個型別，只有當一個物件實現了 protocol 後才有了型別物件。</p><pre>protocol Copyable {<br>    func copy() -&gt; Self<br>}</pre><pre>class MyClass: Copyable {<br>    var num = 1<br>    func copy() -&gt; Self {<br>        let result = type(of: self).init()<br>        result.num  = num<br>        return result<br>    }</pre><pre>    //必須實現<br>    //如果不實現：Constructing an object of class type &#39;Self&#39; with a metatype value must use a &#39;required&#39; initializer。錯誤<br>    required init() {<br>    }<br>}</pre><h3>Mutating Method Requirements</h3><blockquote><em>If you mark a protocol instance method requirement as </em><em>mutating, you don’t need to write the </em><em>mutating keyword when writing an implementation of that method for a class. The </em><em>mutating keyword is only used by structures and enumerations... -</em><a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html"><em>The Swift Programming Language Guide by Apple</em></a></blockquote><p>遵循一個包含Mutating的Protocol時，列舉跟結構定義時必須加上mutating關鍵字，而類別定義時則不用加上。</p><pre>protocol Togglable {<br>    mutating func toggle()<br>}</pre><pre>enum OnOffSwitch: Togglable {<br>    case off, on<br>    mutating func toggle() {<br>        switch self {<br>        case .off:<br>            self = .on<br>        case .on:<br>            self = .off<br>        }<br>    }<br>}<br>var lightSwitch = OnOffSwitch.off<br>lightSwitch.toggle()</pre><h3>Initializer Requirements</h3><blockquote><em>You don’t need to mark protocol initializer implementations with the </em><em>required modifier on classes that are marked with the </em><em>final modifier, because final classes can’t subclassed. For more about the </em><em>final modifier... -</em><a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html"><em>The Swift Programming Language Guide by Apple</em></a></blockquote><p>當一個類別遵從一個含有初始化建構器 (init) 無論是指定或是convenient初始化建構器都需要加上 require，確保所有子類別也有定初始化建構器。若類別為final，則不需要添加required 。</p><pre>protocol SomeProtocol {<br>    init(someParameter: Int)<br>}</pre><pre>class SomeClass: SomeProtocol {<br>    required init(someParameter: Int) {<br>        // initializer implementation goes here<br>    }<br>}</pre><pre>class SomeSubClass: SomeClass, SomeProtocol {<br>    // 必須同時加上 required 和 override<br>		// required 來自 Someprotocl 的 conformance<br>		// override 來自 SuperClass<br>    required override init() {<br>        // 建構器的內容<br>    }<br>}</pre><h3>Protocols as Types</h3><ul><li>大寫開</li><li>作為函式、方法或初始化建構器的參數型別或返回值型別。</li><li>作為常數、變數或屬性的型別。</li><li>作為陣列、字典或其他集合中的元素型別。</li></ul><pre>class Dice {<br>    let sides: Int<br>    let generator: RandomNumberGenerator<br>    init(sides: Int, generator: RandomNumberGenerator) {<br>        self.sides = sides<br>        self.generator = generator<br>    }<br>    func roll() -&gt; Int {<br>        return Int(generator.random() * Double(sides)) + 1<br>    }<br>}</pre><h3>Delegation-委託</h3><blockquote><em>Delegation is a design pattern that enables a class or structure to hand off (or </em>delegate<em>) some of its responsibilities to an instance of another type. -</em><a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html"><em>The Swift Programming Language Guide by Apple</em></a></blockquote><blockquote><em>Delegate — 將特定的工作、職責、權利等給予別人，讓他們為你完成。</em></blockquote><h3>Delegating protocol — 委託協議</h3><pre>protocol DiceGame {<br>    var dice: Dice { get }<br>    func play()<br>}<br>protocol DiceGameDelegate: AnyObject {<br>    func gameDidStart(_ game: DiceGame)<br>    func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)<br>    func gameDidEnd(_ game: DiceGame)<br>}</pre><ul><li>Why AnyObject?</li></ul><p>表示此Protocol 只能應用於 Reference Type → class (非 struct / enum)</p><ul><li>AnyObject / any 差別？</li></ul><p>表示此Protocol 只能應用於 Reference Type → class (非 struct / enum)</p><ul><li>Any 跟 AnyObject的差別</li></ul><p><strong><em>Any</em></strong>：它可以代表任何型別的類別 (class)、結構 (struct)、列舉 (enum)，包括函式和可選型別，基本上可以說是任何東西。</p><p><strong><em>AnyObject</em></strong>：它指的是類別的任何實例。這只在使用<a href="https://www.appcoda.com.tw/value-type-and-reference-type/">參考型別 (reference type)</a> 時，才能派上用場。這就相等於 Objective-C 中等的 ‘id’。</p><pre>class SnakesAndLadders: DiceGame {<br>    let finalSquare = 25<br>    let dice = Dice(sides: 6, generator: LinearCongruentialGenerator())<br>    var square = 0<br>    var board: [Int]<br>    init() {<br>        board = Array(repeating: 0, count: finalSquare + 1)<br>        board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02<br>        board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08<br>    }<br>    weak var delegate: DiceGameDelegate?<br>    func play() {<br>        square = 0<br>        delegate?.gameDidStart(self)<br>        gameLoop: while square != finalSquare {<br>            let diceRoll = dice.roll()<br>            delegate?.game(self, didStartNewTurnWithDiceRoll: diceRoll)<br>            switch square + diceRoll {<br>            case finalSquare:<br>                break gameLoop<br>            case let newSquare where newSquare &gt; finalSquare:<br>                continue gameLoop<br>            default:<br>                square += diceRoll<br>                square += board[square]<br>            }<br>        }<br>        delegate?.gameDidEnd(self)<br>    }<br>}</pre><pre>class DiceGameTracker: DiceGameDelegate {<br>    var numberOfTurns = 0<br>    func gameDidStart(_ game: DiceGame) {<br>        numberOfTurns = 0<br>        if game is SnakesAndLadders {<br>            print(&quot;Started a new game of Snakes and Ladders&quot;)<br>        }<br>        print(&quot;The game is using a \\(game.dice.sides)-sided dice&quot;)<br>    }<br>    func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) {<br>        numberOfTurns += 1<br>        print(&quot;Rolled a \\(diceRoll)&quot;)<br>    }<br>    func gameDidEnd(_ game: DiceGame) {<br>        print(&quot;The game lasted for \\(numberOfTurns) turns&quot;)<br>    }<br>}</pre><pre>let tracker = DiceGameTracker()<br>let game = SnakesAndLadders()<br>game.delegate = tracker<br>game.play()<br>// Started a new game of Snakes and Ladders<br>// The game is using a 6-sided dice<br>// Rolled a 3<br>// Rolled a 5<br>// Rolled a 4<br>// Rolled a 5<br>// The game lasted for 4 turns</pre><p>DiceGameDelegate 協議可以被任意類型遵循，用來追踪 DiceGame 的遊戲過程。</p><h3>Delegate — 代理對象</h3><pre>weak var delegate: DiceGameDelegate?</pre><blockquote><em>To </em><strong><em>prevent strong reference cycles</em></strong><em>, delegates are declared as </em><strong><em>weak</em></strong><em> references.</em></blockquote><ul><li>delegate 為 optional 性質，初始值為nil</li><li>DiceGamDelegateProtocol 為 class-only (AnyObject) ，delegate 遵從了DiceGameDelegate的實例，delegate 運用在 class 裡面，為 Reference Type，所以需要用 weak 來去避免 references cycle。 ⇒ SnakesAndLadders own DiceGameTracker, DiceGameTracker的func own SnakesAndLadders</li></ul><pre>let tracker = DiceGameTracker()<br>let game = SnakesAndLadders()<br>game.delegate = tracker<br>game.play()<br>// Started a new game of Snakes and Ladders<br>// The game is using a 6-sided dice<br>// Rolled a 3<br>// Rolled a 5<br>// Rolled a 4<br>// Rolled a 5<br>// The game lasted for 4 turns</pre><h3>Adding Protocol Conformance with an Extension</h3><blockquote><em>Existing instances of a type automatically adopt and conform to a protocol when that conformance is added to the instance’s type in an extension.</em></blockquote><pre>protocol TextRepresentable {<br>    var textualDescription: String { get }<br>}</pre><pre>extension Dice: TextRepresentable {<br>    var textualDescription: String {<br>        return &quot;A \\(sides)-sided dice&quot;<br>    }<br>}</pre><pre>extension SnakesAndLadders: TextRepresentable {<br>    var textualDescription: String {<br>        return &quot;A game of Snakes and Ladders with \\(finalSquare) squares&quot;<br>    }<br>}</pre><pre>let d12 = Dice(sides: 12, generator: LinearCongruentialGenerator()) print(d12.textualDescription) // Prints &quot;A 12-sided dice&quot;  print(game.textualDescription) // Prints &quot;A game of Snakes and Ladders with 25 squares&quot;</pre><h3>Conditionally Conforming to a Protocol</h3><pre>extension Array: TextRepresentable where Element: TextRepresentable {<br>    var textualDescription: String {<br>        let itemsAsText = self.map { $0.textualDescription }<br>        return &quot;[&quot; + itemsAsText.joined(separator: &quot;, &quot;) + &quot;]&quot;<br>    }<br>}<br>let myDice = [d6, d12]<br>print(myDice.textualDescription)<br>// Prints &quot;[A 6-sided dice, A 12-sided dice]&quot;</pre><p>讓 Array 的 class 只要在存储遵循 TextRepresentable protocol的元素时就遵循 TextRepresentable protocol。</p><h3>Adopting a Protocol Using a Synthesized Implementation</h3><p>Swift 提供的 Equatable, Hashable, 跟 Comparable Protocol，使用時不需要再重寫。</p><h4>Equatable</h4><ul><li>Structures that have only stored properties that conform to the Equatable protocol</li><li>Enumerations that have only associated types that conform to the Equatable protocol</li><li>Enumerations that have no associated types</li><li>When conform to Equatable, provide a method that returns whether the given object and self are equal.</li></ul><pre>struct Vector3D: Equatable {<br>    var x = 0.0, y = 0.0, z = 0.0<br>}<br><br>let twoThreeFour = Vector3D(x: 2.0, y: 3.0, z: 4.0)<br>let anotherTwoThreeFour = Vector3D(x: 2.0, y: 3.0, z: 4.0)<br>if twoThreeFour == anotherTwoThreeFour {<br>    print(&quot;These two vectors are also equivalent.&quot;)<br>}<br>// Prints &quot;These two vectors are also equivalent.&quot;<br><br>enum Status: Equatable {<br>    case onTime<br>    case delayed(minute: Int, second: Int)<br>    case notComing(people: People)<br>}<br><br>struct People: Equatable {<br>    var name: String<br>}</pre><h4>Hashable — conform equatable</h4><ul><li>For a struct, all its stored properties must conform to Hashable.</li><li>For an enum, all its associated values must conform to Hashable.</li><li>When conform to Hashable, provide a method that returns the <em>hash value</em> of self.</li></ul><pre>/// A point in an x-y coordinate system.<br>struct GridPoint {<br>    var x: Int<br>    var y: Int<br>}<br><br>extension GridPoint: Hashable {<br>    static func == (lhs: GridPoint, rhs: GridPoint) -&gt; Bool {<br>        return lhs.x == rhs.x &amp;&amp; lhs.y == rhs.y<br>    }<br><br>    func hash(into hasher: inout Hasher) {<br>        hasher.combine(x) // 參考屬性製作 Hash value<br>        hasher.combine(y) // 參考屬性製作 Hash value<br>    }<br>}</pre><h4>Comparable — conform equatable</h4><pre>enum SkillLevel: Comparable {<br>    case beginner<br>    case intermediate<br>    case expert(stars: Int)<br>}<br>var levels = [SkillLevel.intermediate, SkillLevel.beginner,<br>              SkillLevel.expert(stars: 5), SkillLevel.expert(stars: 3)]<br><br>for level in levels.sorted(by: &lt;) {<br>    print(level)<br><br>}<br>// Prints &quot;beginner&quot;<br>// Prints &quot;intermediate&quot;<br>// Prints &quot;expert(stars: 3)&quot;<br>// Prints &quot;expert(stars: 5)&quot;</pre><blockquote>Enum 裡的 beginner / intermediate swift是用什麼邏輯在排序的？<br> ⇒ 宣告時的順序</blockquote><h3>Collections of Protocol Type</h3><p>遵從相同Protocol 的物件作為相同Type 存放在Array / Dictionary</p><pre>let things: [TextRepresentable] = [game, d12]<br>for thing in things {<br>    print(thing.textualDescription)<br>}<br>// A game of Snakes and Ladders with 25 squares<br>// A 12-sided dic</pre><ul><li>thing 為 TextRepresentable 類型 而不是 Dice，DiceGame 類型</li></ul><h3>Protocol Inheritance</h3><p>可以繼承多個Protocol</p><pre>protocol PrettyTextRepresentable: TextRepresentable {<br>    var prettyTextualDescription: String { get }<br>}</pre><pre>//遵從 TextRepresentable &amp; PrettyTextRepresentable 的協定<br>extension SnakesAndLadders: PrettyTextRepresentable {<br>    var prettyTextualDescription: String {<br>        var output = textualDescription + &quot;:\\n&quot;<br>        for index in 1...finalSquare {<br>            switch board[index] {<br>            case let ladder where ladder &gt; 0:<br>                output += &quot;▲ &quot;<br>            case let snake where snake &lt; 0:<br>                output += &quot;▼ &quot;<br>            default:<br>                output += &quot;○ &quot;<br>            }<br>        }<br>        return output<br>    }<br>}</pre><pre>print(game.prettyTextualDescription)<br>// A game of Snakes and Ladders with 25 squares:<br>// ○ ○ ▲ ○ ○ ▲ ○ ○ ▲ ▲ ○ ○ ○ ▼ ○ ○ ○ ○ ▼ ○ ○ ▼ ○ ▼ ○</pre><p>任何遵循 PrettyTextRepresentable 的 class 在满足該 protocol 的要求时，也必须满足 TextRepresentable protocol 的要求。</p><p>Protocols组合使用 SomeProtocol &amp; AnotherProtocol 的形式。可以列举任意数量的協議，用和符號（&amp;）分開。</p><p>下面的例子中，將Named 和 Aged 两个協議按照上述语法组合成一个協議，作为函数参数的類型：</p><pre>protocol Named {<br>    var name: String { get }<br>}<br>protocol Aged {<br>    var age: Int { get }<br>}<br>struct Person: Named, Aged {<br>    var name: String<br>    var age: Int<br>}<br>func wishHappyBirthday(to celebrator: Named &amp; Aged) {<br>    print(&quot;Happy birthday, \\(celebrator.name), you&#39;re \\(celebrator.age)!&quot;)<br>}<br>let birthdayPerson = Person(name: &quot;Malcolm&quot;, age: 21)<br>wishHappyBirthday(to: birthdayPerson)<br>// Prints &quot;Happy birthday, Malcolm, you&#39;re 21!&quot;</pre><h3>OOP? POP？ 蘋果官方宣稱「<a href="https://developer.apple.com/videos/play/wwdc2015-408/?time=868">從核心來看，Swift 其實是協定導向 (Protocol-Oriented) 的程式語言</a> 」</h3><p>減少重複的Code、權責分開，把每個元件的功能定義清楚，將重複的部分拉出來統一管理。 有兩種方式可以做到以上的目標，其中一個是利用OOP物件導向的的特性-繼承 (inheritance)來去將會重複的部分放在父類別，再由子類別去繼承，但也因為物件導向的特性，子類別會繼承父類別所有內容；有可能會違反了 SOLID 的 介面隔離原則（Interface Segregation Principle)。</p><p>另一種的方式就是使用 Composition Pattern 的方式將功能做成組件，讓需要的模組去組合取用。</p><h3>Why Protocols?</h3><blockquote><strong><em>Protocols</em></strong><em> vs. </em><strong><em>Inheritance</em></strong></blockquote><p>👉 In <strong>SOLID</strong> principle, Interface segregation principle states that： A client should never be forced to implement an interface that it doesn’t use or clients shouldn’t be forced to depend on methods they do not use.</p><p>Protocols 解決了 <strong>Inheritance 會繼承到父類別連可能不需要的基因也一併繼承，其可能違反了SOLID的 Interface Segregation 介面隔離原則)</strong></p><p>Swift2.0 之後 針對 Composition Pattern 提出了方便的工具，Protocol Extensions， 透過 extension 的語法去實作 protocol中定義的 interface，在 conform protocol 的時候，就算不實作這些 interface，編譯器也會給過，因為這些 interface 已經在 extension 中被實作了。</p><pre>protocol Sound {<br>    func makeSound()<br>}</pre><pre>extension Sound {<br>    func makeSound() {<br>        print(&quot;Wow&quot;)<br>    }<br>}</pre><pre>protocol Flyable {<br>    func fly()<br>}</pre><pre>extension Flyable {<br>    func fly() {<br>        print(&quot;✈️&quot;)<br>    }<br>}</pre><pre>class Airplane: Flyable { }<br>class Pigeon: Sound, Flyable { }<br>class Penguin: Sound { }</pre><pre>let pigeon = Pigeon()<br>pigeon.fly()  // prints ✈️<br>pigeon.makeSound() // prints Wow</pre><h3>Checking for Protocol Conformance</h3><p>使用 is , as operator 確認 protocol 的一致性</p><pre>protocol HasArea {<br>    var area: Double { get }<br>}</pre><pre>////////////////////////////////////////////////////////</pre><pre>class Circle: HasArea {<br>    let pi = 3.1415927<br>    var radius: Double<br>    var area: Double { return pi * radius * radius }<br>    init(radius: Double) { self.radius = radius }<br>}<br>class Country: HasArea {<br>    var area: Double<br>    init(area: Double) { self.area = area }<br>}<br>class Animal {<br>    var legs: Int<br>    init(legs: Int) { self.legs = legs }<br>}</pre><pre>////////////////////////////////////////////////////////</pre><pre>let objects: [AnyObject] = [<br>    Circle(radius: 2.0),<br>    Country(area: 243_610),<br>    Animal(legs: 4)<br>]</pre><pre>////////////////////////////////////////////////////////</pre><pre>for object in objects {<br>    if let objectWithArea = object as? HasArea {<br>        print(&quot;Area is \\(objectWithArea.area)&quot;)<br>    } else {<br>        print(&quot;Something that doesn&#39;t have an area&quot;)<br>    }<br>}</pre><pre>for object in objects {<br>    if object is HasArea {<br>        print(&quot;object is HasArea type&quot;)<br>    } else {<br>        print(&quot;object is NOT HasArea type&quot;)<br>    }<br>}</pre><pre>// Area is 12.5663708<br>// Area is 243610.0<br>// Something that doesn&#39;t have an area</pre><pre>// object is HasArea type<br>// object is HasArea type<br>// object is NOT HasArea type</pre><h3>Adding Constraints to Protocol Extensions</h3><pre>extension Collection where Element: Equatable {<br>    func allEqual() -&gt; Bool {<br>        for element in self {<br>            if element != self.first {<br>                return false<br>            }<br>        }<br>        return true<br>    }<br>}</pre><pre>let equalNumbers = [100, 100, 100, 100, 100]<br>let differentNumbers = [100, 100, 200, 100, 200]</pre><pre>print(equalNumbers.allEqual())<br>// Prints &quot;true&quot;<br>print(differentNumbers.allEqual())<br>// Prints &quot;false&quot;</pre><h3>Optional Protocol Requirements</h3><p>在預設的情況下，Swift中的 protocol內的方法都必須要實作，若想要將方法改成 Optional 性質，可以透過下方式</p><ol><li>使用 @objc 屬性標記</li></ol><p>@objc 屬性標記的協議只能被從 Objective-C class 或其他 @objc class 繼承的 class 採用。它們不能被 struct 或 enum 採用。</p><pre>@objc protocol CounterDataSource {<br>    @objc optional func increment(forCount count: Int) -&gt; Int<br>    @objc optional var fixedIncrement: Int { get }<br>}</pre><pre>class Counter {<br>    var count = 0<br>    var dataSource: CounterDataSource?<br>    func increment() {<br>        if let amount = dataSource?.increment?(forCount: count) {<br>            count += amount<br>        } else if let amount = dataSource?.fixedIncrement {<br>            count += amount<br>        }<br>    }<br>}</pre><pre>class ThreeSource: NSObject, CounterDataSource {<br>    let fixedIncrement = 3<br>}</pre><pre>var counter = Counter()<br>counter.dataSource = ThreeSource()<br>for _ in 1...4 {<br>    counter.increment()<br>    print(counter.count)<br>}<br>// 3<br>// 6<br>// 9<br>// 12</pre><pre>class TowardsZeroSource: NSObject, CounterDataSource {<br>    func increment(forCount count: Int) -&gt; Int {<br>        if count == 0 {<br>            return 0<br>        } else if count &lt; 0 {<br>            return 1<br>        } else {<br>            return -1<br>        }<br>    }<br>}</pre><pre>counter.count = -4<br>counter.dataSource = TowardsZeroSource()<br>for _ in 1...5 {<br>    counter.increment()<br>    print(counter.count)<br>}<br>// -3<br>// -2<br>// -1<br>// 0<br>// 0</pre><ol><li>extension 一個預設實作方法:</li></ol><pre>protocol Printable {<br>    func canPrint() -&gt; Bool<br>}</pre><pre>extension Printable {<br>    func canPrint() -&gt; Bool {<br>        return true<br>    }<br>}</pre><h3>Summary</h3><h4>語法上：</h4><p>屬性：</p><ul><li>透過 { get set } 來指定讀寫的屬性</li><li>透過 static / class 來指定型別的屬性</li></ul><p>方法：</p><ul><li>透過 static / class 來指定class的方法</li><li>透過 mutating 來要求實現針對valueType的修改方法</li></ul><p>init要求：</p><ul><li>在Conform的class中 需要使用 required 修飾,確保其子class 也有。</li></ul><h4>As a type：</h4><p>代表某個 instance 所遵從的協議，也可以做成 Array 或 Collection</p><p>Delegate 委託設計模式，用來封裝需要被委託的功能</p><h4><strong>Protocol之間的關係：</strong></h4><p>可繼承、可同時遵循多個Protocol</p><p>透過 is, as? , as! 進行 Conformance 的檢查</p><p>在繼承時 使用 class 來表示 該protocol的職能可以被 class 繼承</p><h4><strong>optional 的 Protocol</strong></h4><p>使用 optional 修飾 propriety、methods、protocol本身 , 同時所有的 optional 與協議本身都必須要使用 @objc 進行修飾，而且只能被 Objective-C 的 class 或者帶有 @objc 的 class 使用。</p><h4>extension:</h4><p>對 instance 使用，讓其遵循某個協議</p><p>對 protocol 使用，可再遵循其他協議，增加 protocol 的一致性 或是 提供預設的實作方法</p><p>使用 where 來增加限制的條件</p><p>資料來源： <a href="https://docs.swift.org/swift-book/LanguageGuide/Protocols.html">https://docs.swift.org/swift-book/LanguageGuide/Protocols.html</a> <a href="https://medium.com/one-two-swift/classes-%E5%92%8C-structure-oop-%E5%92%8C-pop-de4a4b4ffe4b">https://medium.com/one-two-swift/classes-和-structure-oop-和-pop-de4a4b4ffe4b</a></p><p><a href="https://www.hackingwithswift.com/example-code/language/how-to-make-optional-protocol-methods">https://www.hackingwithswift.com/example-code/language/how-to-make-optional-protocol-methods</a></p><p><a href="https://www.appcoda.com.tw/any-anyobject/">https://www.appcoda.com.tw/any-anyobject/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=560135a77454" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elio-iosapp/protocols-delegate-%E9%96%B1%E8%AE%80%E5%BF%83%E5%BE%97%E7%AD%86%E8%A8%98-560135a77454">Protocols &amp; Delegate 閱讀心得筆記</a> was originally published in <a href="https://medium.com/elio-iosapp">iOS 雛鳥學飛之路</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[git 版本管控]]></title>
            <link>https://elio0shin.medium.com/git-%E7%89%88%E6%9C%AC%E7%AE%A1%E6%8E%A7-1bd2810e735b?source=rss-a4d0bfa86011------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bd2810e735b</guid>
            <dc:creator><![CDATA[Elio Shih]]></dc:creator>
            <pubDate>Sun, 01 Aug 2021 22:44:27 GMT</pubDate>
            <atom:updated>2021-08-01T22:44:27.233Z</atom:updated>
            <content:encoded><![CDATA[<p>最近開始了 AppWorksSchool 的 RemoteLearning 的遠端課程，將基本功好好的練起來，這次就來再度學習 git 版本管控吧！</p><h3>什麼是Git? 跟GitHub、GitLab 有什麼差別？</h3><blockquote>Git 是一個在工程師世界裡面稱 “版本管控”的一種系統。由Linux之父 Linus Torvalds 所創作出來的。</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ED1zrvPaYZoaebGAaYkZbA.png" /></figure><p>剛進入工程師世界的我，一開始對於 git、GitHub、GitLab的名詞搞得很混亂，但在深入了解過後，發現其實很簡單的，git 為一個版本管控系統， 而 GitHub、GitLab 則是一個提供遠端儲存空間(Remote Repostiory)，讓我們可以進行存放自己的檔案版本的地方，當然如果我們沒有要將檔案存放在網路上，也可以只單純在我們的電腦上進行git的版本管控。</p><h3>為什麼我們需要git版本管控？</h3><p>在做設計案的時候，我們很常遇到一件事情，就是客戶不斷的改稿，導致於我們專案資料夾內往往會有一下情形：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9jrNAN2BcC03cbrBA62e8Q.png" /></figure><p>沒錯，永遠不間斷的Final檔案，但在工程師的世界裡面也會遇到相同的問題，不管是在跟人合作或是自己進行一項專案的時候，</p><p>專案的版本一多，分成好幾個檔案進行儲存，就不會是一個好辦法。無法很有效地看出每個版本之間的差距(特別是工程師，往往都是一大串英文所組成，在視覺上更不可能一看就知道差別），因此就有了所謂的 版本管控(Version Control)</p><h3>Git的原理</h3><p>簡單來說，我們先將資料夾進行標記，來紀錄在這個資料夾內的變動，確任變動後，寫下本次變動版本的註解，之後就可以將檔案處存到本地或是遠端資料庫囉。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yD1vAac0Fa0Rgk_Boam8Iw.png" /></figure><h3>四大區域</h3><h4>Workspace 工作區</h4><ul><li>進行版本的比對與狀態確認 — Untracked / Tracked / Unmodified / Modified</li></ul><h4>Staging Area 暫存區</h4><ul><li>處存要更新上傳的版本 填寫版本的描述</li></ul><h4>Local Repository 本地端儲存庫</h4><ul><li>咱們資料版本在電腦上的處存地</li></ul><h4>Remote Repository 遠端儲存庫</h4><ul><li>GitLab 、 GitHub 就是屬於遠端儲存庫</li></ul><h3>常用方法</h3><h3>status</h3><p>用來查看目前專案資料夾內的狀況：</p><pre>git status</pre><ul><li>Untracked / 尚紀錄過的檔案</li><li>Tracked / 已紀錄過的的檔案</li><li>Unmodified / 無修修改的檔案</li><li>Modified / 修改過的檔案</li></ul><h3>add</h3><p>透過 add 將新增、修改過的檔案存入 Staging Area</p><pre>git add [檔案名稱] //新增特定檔案<br>git add . //新增所有檔案<br>git add * //新增所有檔案</pre><h3>commit</h3><p>填寫版本的更新資訊、並更新至 Local Repository</p><pre>git commit // 進入vim  填寫commit訊息<br>git commit -m &quot;輸入Commit訊息&quot;</pre><h3>push</h3><p>將 Local Repo 更新至 Remote Repo</p><pre>git push //更新至原本設定的遠端Repo<br>git push [特定遠端repo的URL]</pre><h3>fetch</h3><p>確認Remote Repo內容，將內容建立一份在Local Repo</p><pre>git fetch</pre><h3>merge</h3><p>將 Local Repo的內容合併到 ＷorkSpace</p><pre>git merge</pre><h3>pull</h3><p>進行 fetch + merge</p><pre>git pull</pre><h3>log</h3><p>查詢版本更動的紀錄</p><pre>git log</pre><h3>diff</h3><p>顯示檔案在 Workspace 與 Staging Area 差異</p><pre>git diff</pre><p>以上就是 Git 的初步基本知識哩，之後有空的話在來整裡一些關於分支Branch、跟一些實作Git的文章吧:D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bd2810e735b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CamelCase Method]]></title>
            <link>https://medium.com/elio-iosapp/camelcase-method-5a4bce2af2fb?source=rss-a4d0bfa86011------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a4bce2af2fb</guid>
            <category><![CDATA[codewars]]></category>
            <dc:creator><![CDATA[Elio Shih]]></dc:creator>
            <pubDate>Fri, 18 Jun 2021 23:44:32 GMT</pubDate>
            <atom:updated>2021-11-29T07:08:01.597Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_X68P-b3Ygc025G4LXuzwA.png" /></figure><h3>Description:</h3><p>Write a simple camelCase function for strings. All words must have their first letter capitalized and all spaces removed.</p><p>For instance:</p><pre>camelCase(&quot;hello case&quot;);// ==&gt; &quot;HelloCase&quot;camelCase(&quot;camel case word&quot;);// ==&gt; &quot;CamelCaseWord&quot;</pre><h3>TryCode:</h3><pre>func camelCase (_ str: String) -&gt; String{<br>    <br>    var newStr = &quot;&quot;<br>    var isAfterSapce = true<br>    for chacter in str{<br>      if chacter.isWhitespace{<br>                isAfterSapce = true<br>             continue<br>      }else{<br>            if isAfterSapce {<br>                newStr.append(&quot;\\(chacter.uppercased())&quot;)<br>                isAfterSapce = false<br>            }else{<br>                newStr.append(&quot;\\(chacter)&quot;)<br>      }</pre><pre>    }<br>}<br>    return newStr<br>}</pre><h3>BetterCode:</h3><pre>func camelCase(_ str: String) -&gt; String {<br>  return str.capitalized.replacingOccurrences(of: &quot; &quot;, with: &quot;&quot;)<br>}</pre><h3>Note:</h3><h3>.capitalized</h3><p>var capitalized: [String](&lt;https://developer.apple.com/documentation/swift/string&gt;) { get }</p><p>自動把每段文字的首字便大寫</p><h3>replacingOccurrences(of:with:)</h3><p>func replacingOccurrences(of target: [String](&lt;https://developer.apple.com/documentation/swift/string&gt;), with replacement: [String](&lt;https://developer.apple.com/documentation/swift/string&gt;)) -&gt; [String](&lt;https://developer.apple.com/documentation/swift/string&gt;)</p><p>替換文字</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a4bce2af2fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elio-iosapp/camelcase-method-5a4bce2af2fb">CamelCase Method</a> was originally published in <a href="https://medium.com/elio-iosapp">iOS 雛鳥學飛之路</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[004 Find the nth Digit of a Number]]></title>
            <link>https://medium.com/elio-iosapp/004-find-the-nth-digit-of-a-number-519864e166fc?source=rss-a4d0bfa86011------2</link>
            <guid isPermaLink="false">https://medium.com/p/519864e166fc</guid>
            <category><![CDATA[codewars]]></category>
            <dc:creator><![CDATA[Elio Shih]]></dc:creator>
            <pubDate>Wed, 16 Jun 2021 23:42:49 GMT</pubDate>
            <atom:updated>2021-11-29T07:08:41.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3gxLJPBOarTDaWqqadVHeg.png" /></figure><h3>Instructions:</h3><h4>Description</h4><p>Complete the function that takes two numbers as input, num and nth and return the nth digit of num (counting from right to left).</p><h4>Note</h4><ul><li>If num is negative, ignore its sign and treat it as a positive value</li><li>If nth is not positive, return 1</li><li>Keep in mind that 42 = 00042. This means that findDigit(42, 5) would return 0</li></ul><h4>Examples</h4><pre>findDigit(5673, 4)     returns 5<br>findDigit(129, 2)      returns 2<br>findDigit(-2825, 3)    returns 8<br>findDigit(-456, 4)     returns 0<br>findDigit(0, 20)       returns 0<br>findDigit(65, 0)       returns -1<br>findDigit(24, -8)      returns -1</pre><h3>TryCode:</h3><pre>func findDigit(_ num:Int, _ nth: Int) -&gt; Int {</pre><pre>    var numToString = &quot;\\(num)&quot;</pre><pre>    if nth &lt;= 0 {<br>        return -1<br>    }else{</pre><pre>        if numToString.count &gt;= nth{<br>            var offsetNumber = nth<br>            offsetNumber.negate()<br>            offsetNumber + 1<br>            return<br>            Int(&quot;\\(numToString[numToString.index(numToString.endIndex, offsetBy: offsetNumber)])&quot; ) ?? 0<br>        }else{</pre><pre>        return  0</pre><pre>        }</pre><pre>    }<br>}</pre><h3>BetterCode:</h3><pre>func findDigit(_ num: Int, _ nth: Int) -&gt; Int {<br>  let positive = abs(num)<br>  <br>  guard nth &gt; 0 else { return -1 }<br>  guard positive &gt; 0 else { return 0 }<br>  guard nth &gt; 1 else { return positive % 10 }<br>  <br>  return findDigit(positive / 10, nth - 1)<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=519864e166fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elio-iosapp/004-find-the-nth-digit-of-a-number-519864e166fc">004 Find the nth Digit of a Number</a> was originally published in <a href="https://medium.com/elio-iosapp">iOS 雛鳥學飛之路</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[003 Give me a Diamond]]></title>
            <link>https://medium.com/elio-iosapp/003-give-me-a-diamond-8632469c47b0?source=rss-a4d0bfa86011------2</link>
            <guid isPermaLink="false">https://medium.com/p/8632469c47b0</guid>
            <category><![CDATA[codewars]]></category>
            <dc:creator><![CDATA[Elio Shih]]></dc:creator>
            <pubDate>Wed, 16 Jun 2021 10:14:04 GMT</pubDate>
            <atom:updated>2021-11-29T07:09:05.751Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8XpuCJLZDkdbPeXE9JhXzQ.png" /></figure><h3>Give me a Diamond</h3><h3>Instructions:</h3><p>In this kata you get the start number and the end number of a region and should return the count of all numbers except numbers with a 5 in it. The start and the end number are both inclusive!</p><p>Examples:</p><pre>1,9 -&gt; 1,2,3,4,6,7,8,9 -&gt; Result 8<br>4,17 -&gt; 4,6,7,8,9,10,11,12,13,14,16,17 -&gt; Result 12</pre><p>The result may contain fives. ;-)The start number will always be smaller than the end number. Both numbers can be also negative!</p><p>I’m very curious for your solutions and the way you solve it. Maybe someone of you will find an easy pure mathematics solution.</p><p>Have fun coding it and please don’t forget to vote and rank this kata! :-)</p><p>I have also created other katas. Take a look if you enjoyed this kata!</p><p>Jamie is a programmer, and James’ girlfriend. She likes diamonds, and wants a diamond string from James. Since James doesn’t know how to make this happen, he needs your help.</p><h3>Task</h3><p>You need to return a string that looks like a diamond shape when printed on the screen, using asterisk (*) characters. Trailing spaces should be removed, and every line must be terminated with a newline character (\\n).</p><p>Return null/nil/None/... if the input is an even number or negative, as it is not possible to print a diamond of even or negative size.</p><h3>Examples</h3><p>A size 3 diamond:</p><pre>*<br>***<br> *</pre><p>…which would appear as a string of &quot; *\\n***\\n *\\n&quot;</p><p>A size 5 diamond:</p><pre>*<br> ***<br>*****<br> ***<br>  *</pre><p>…that is:</p><pre>&quot;  *\\n ***\\n*****\\n ***\\n  *\\n&quot;</pre><h3>TryCode:</h3><pre>func diamond(_ size: Int) -&gt; String? {<br>    <br>    var p = &quot;&quot;<br>    if (size &gt; 1 &amp;&amp; size % 2 != 0){<br>        var d = 1<br>        var b = ((size+1)/2)-1<br>        for _ in 1...((size+1)/2){<br>           <br>            if b != 0{<br>                for _ in 1...b{<br>                    p += &quot; &quot;<br>                }<br>                b -= 1<br>                for _ in 1...d{<br>                    p += &quot;*&quot;<br>                }<br>                d += 2<br>                p += &quot;\\n&quot;<br>            }<br>            else{<br>                for _ in 1...d{<br>                    p += &quot;*&quot;<br>                }<br>                p += &quot;\\n&quot;<br>            }<br>            <br>        }<br>        b += 1<br>        d -= 2<br>        for _ in 1...(((size+1)/2)-1){<br>            for _ in 1...b{<br>                    p += &quot; &quot;<br>            }<br>            b += 1<br>            for _ in 1...d{<br>                    p += &quot;*&quot;<br>            }<br>                d -= 2<br>                p += &quot;\\n&quot;<br>        }</pre><pre>        return p<br>    }else if (size == 1){<br>        return &quot;*&quot;<br>    }<br>    <br>   return nil<br>}</pre><h3>BetterCode:</h3><pre>func diamond(_ size: Int) -&gt; String? {<br>    guard size % 2 == 1 else {<br>        return nil<br>    }<br>    var diamond = &quot;&quot;<br>    let centerRow = size/2 + 1<br>    for row in 1...size {<br>        let spaces = abs(centerRow - row)<br>        diamond += String(repeating: &quot; &quot;, count: spaces) + String(repeating: &quot;*&quot;, count: size-spaces*2) + &quot;\\n&quot;<br>    }<br>    return diamond<br>}</pre><h3>Note:</h3><p><a href="https://developer.apple.com/documentation/swift/2885649-abs/">abs(_:)</a></p><pre>func abs&lt;T&gt;(_ x: T) -&gt; T where T : Comparable, T : SignedNumeric</pre><p>Returns the absolute value of the given number.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8632469c47b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elio-iosapp/003-give-me-a-diamond-8632469c47b0">003 Give me a Diamond</a> was originally published in <a href="https://medium.com/elio-iosapp">iOS 雛鳥學飛之路</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[002 Don’t give me Five]]></title>
            <link>https://medium.com/elio-iosapp/002-dont-give-me-five-codewars-daily-challenge-ed8964e0dc04?source=rss-a4d0bfa86011------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed8964e0dc04</guid>
            <category><![CDATA[codewars]]></category>
            <dc:creator><![CDATA[Elio Shih]]></dc:creator>
            <pubDate>Mon, 14 Jun 2021 22:19:03 GMT</pubDate>
            <atom:updated>2021-11-29T07:09:55.518Z</atom:updated>
            <content:encoded><![CDATA[<h3>002 Don’t give me Five/Codewars — Daily challenge</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNDiJbUA3j0XM0iMkBGtaw.png" /></figure><h3>Don’t give me five!</h3><h3>Instructions:</h3><p>In this kata you get the start number and the end number of a region and should return the count of all numbers except numbers with a 5 in it. The start and the end number are both inclusive!</p><p>Examples:</p><pre>1,9 -&gt; 1,2,3,4,6,7,8,9 -&gt; Result 8<br>4,17 -&gt; 4,6,7,8,9,10,11,12,13,14,16,17 -&gt; Result 12</pre><p>The result may contain fives. ;-)The start number will always be smaller than the end number. Both numbers can be also negative!</p><p>I’m very curious for your solutions and the way you solve it. Maybe someone of you will find an easy pure mathematics solution.</p><p>Have fun coding it and please don’t forget to vote and rank this kata! :-)</p><p>I have also created other katas. Take a look if you enjoyed this kata!</p><h3>TryCode:</h3><pre>func dontGiveMeFive(_ start: Int, _ end: Int) -&gt; Int {</pre><pre>    var count = 0<br>    var isHaneFive = false<br>    for number in start...end{<br>        for character in &quot;\\(number)&quot;{<br>            if character == &quot;5&quot;{<br>                isHaneFive = true<br>                break<br>            }else{<br>                isHaneFive = false<br>            }<br>            }<br>        if isHaneFive == false{<br>            count += 1<br>         <br>        }<br>    }</pre><pre>    return count</pre><pre>}</pre><h3>BetterCode:</h3><pre>func dontGiveMeFive(_ start: Int, _ end: Int) -&gt; Int {<br>  return (start...end).filter { !String($0).contains(&quot;5&quot;) }.count<br>}</pre><h3>Note:</h3><p><a href="https://developer.apple.com/documentation/swift/set/1540013-contains/">contains(_:)</a></p><pre>func contains(_ member: Element) -&gt; Bool</pre><p>Returns a Boolean value that indicates whether the given element exists in the set.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed8964e0dc04" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elio-iosapp/002-dont-give-me-five-codewars-daily-challenge-ed8964e0dc04">002 Don’t give me Five</a> was originally published in <a href="https://medium.com/elio-iosapp">iOS 雛鳥學飛之路</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[001 Count the Digit]]></title>
            <link>https://medium.com/elio-iosapp/001-count-the-digit-52d80d69329?source=rss-a4d0bfa86011------2</link>
            <guid isPermaLink="false">https://medium.com/p/52d80d69329</guid>
            <category><![CDATA[codewars]]></category>
            <dc:creator><![CDATA[Elio Shih]]></dc:creator>
            <pubDate>Mon, 14 Jun 2021 05:59:36 GMT</pubDate>
            <atom:updated>2021-11-29T07:10:24.702Z</atom:updated>
            <content:encoded><![CDATA[<h3>001 Count the Digit/Codewars — Daily challenge</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gfVSFwAUyozFgwhiwmwNmw.png" /></figure><h3>Description:</h3><p>Take an integer n (n &gt;= 0) and a digit d (0 &lt;= d &lt;= 9) as an integer.</p><p>Square all numbers k (0 &lt;= k &lt;= n) between 0 and n.</p><p>Count the numbers of digits d used in the writing of all the k**2.</p><p>Call nb_dig (or nbDig or ...) the function taking n and d as parameters and returning this count.</p><h3>Examples:</h3><p>n = 10, d = 1<br>the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100<br>We are using the digit 1 in: 1, 16, 81, 100. The total count is then 4.</p><p>nb_dig(25, 1) returns 11 since<br>the k*k that contain the digit 1 are:<br>1, 16, 81, 100, 121, 144, 169, 196, 361, 441.<br>So there are 11 digits 1 for the squares of numbers between 0 and 25.</p><h3>TryCode:</h3><pre>func nbDig(_ n: Int, _ d: Int) -&gt; Int {<br>    var count = 0<br>    for i in 0...n {<br>        let square = &quot;\\(i*i)&quot;<br>        for digit in square{<br>         if &quot;\\(digit)&quot; == &quot;\\(d)&quot;{<br>             count += 1<br>         }<br>        }<br>    }<br>    return count<br>   }</pre><h3>BetterCode:</h3><pre>func nbDig(_ n: Int, _ d: Int) -&gt; Int {<br>    return (0...n).map{&quot;\\($0 * $0)&quot;.filter { $0 == Character(&quot;\\(d)&quot;)}}.flatMap { $0 }.count<br>}</pre><h3>Note:</h3><p><a href="https://developer.apple.com/documentation/swift/array/3017522-map">Map(_:)</a></p><pre>func map&lt;T&gt;(_ transform: (Element) throws -&gt; T) rethrows -&gt; [T]</pre><ul><li>transform 表示傳入的一個 function 或 closure，用來轉換陣列裡的元素。輸入參數與回傳結果型別可以不同。</li><li>map() 回傳結果為陣列。</li></ul><p><a href="https://developer.apple.com/documentation/swift/dictionary/2995335-filter/">Filter(_:)</a></p><pre>func filter(_ isIncluded: (Character) throws -&gt; Bool) rethrows -&gt; (__owned String)</pre><ul><li>includeElement 表示傳入的一個 function 或 closure，判斷陣列個元素是否符合條件，符合則則進行回傳。</li><li>filter() 回傳結果為陣列。</li></ul><p>FlatMap</p><p>func flatMap&lt;SegmentOfResult&gt;(_ transform: (Element) throws -&gt; SegmentOfResult) rethrows -&gt; [SegmentOfResult.Element] where SegmentOfResult : Sequence</p><ul><li>transform 表示傳入的一個 function 或 closure，用來轉換陣列裡的元素。輸入參數與回傳結果型別可以不同。</li><li>等同於先執行map()在執行Flatten將元素取出來形成一個新陣列</li></ul><p>“$0” In closures</p><blockquote><em>“Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure’s arguments by the names $0, $1, $2, and so on.”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52d80d69329" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elio-iosapp/001-count-the-digit-52d80d69329">001 Count the Digit</a> was originally published in <a href="https://medium.com/elio-iosapp">iOS 雛鳥學飛之路</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【App Dev-SwiftUI心得筆記】#3 以AirTable作為簡單資料庫進行串連API]]></title>
            <link>https://elio0shin.medium.com/app-dev-swiftui%E5%BF%83%E5%BE%97%E7%AD%86%E8%A8%98-3-%E4%BB%A5airtable%E4%BD%9C%E7%82%BA%E7%B0%A1%E5%96%AE%E8%B3%87%E6%96%99%E5%BA%AB%E9%80%B2%E8%A1%8C%E4%B8%B2%E9%80%A3api-c51dc7fd5305?source=rss-a4d0bfa86011------2</link>
            <guid isPermaLink="false">https://medium.com/p/c51dc7fd5305</guid>
            <dc:creator><![CDATA[Elio Shih]]></dc:creator>
            <pubDate>Fri, 21 May 2021 10:41:08 GMT</pubDate>
            <atom:updated>2021-05-21T10:43:08.732Z</atom:updated>
            <content:encoded><![CDATA[<h3>Goal: 完成Category Art頁面</h3><h3>Used Tools:</h3><p>AirTable / URLSession / SDWebimage</p><h3>製作Category DataBase</h3><p>在AirTable建立簡易的資料庫，並獲取API格式</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NcrKDrduk0TchrqdoyWLiw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGs6zvTlKNQv1PrVto7nVw.png" /></figure><p>建立解析ＪＳＯＮ用的protocol型別</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53730715cbe28c84b56db5f2b90ae93f/href">https://medium.com/media/53730715cbe28c84b56db5f2b90ae93f/href</a></iframe><h3>使用URLSession 獲取Data,進行JSON解析</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2719e3af71cd2ab6aeaaa26e6aca505d/href">https://medium.com/media/2719e3af71cd2ab6aeaaa26e6aca505d/href</a></iframe><h3>將解析後的資料顯示在畫免上</h3><p>SDWebimage → 用來設定顯示網路上圖片的Library</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c893d0d460b9ed92013643c131144bf/href">https://medium.com/media/8c893d0d460b9ed92013643c131144bf/href</a></iframe><h3>顯示結果</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*mHGvFixkZk13yyhP5xl-gA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*CDcmgeiAGadpvhVDnaKXCw.gif" /><figcaption>成功畫面/解析失敗畫面</figcaption></figure><p>Clean Code!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*-myZenxBEXiVW-EVdZ5Oeg.png" /></figure><h4>DateFromAirtable</h4><pre>struct AirtableRecords:Decodable {<br>   var records : [AirTableRecord]<br>}<br>struct AirTableRecord: Decodable,Hashable {<br>    var id : String<br>    var fields : Place<br>}<br><br>struct Place: Decodable,Hashable {<br>    var name,thumbnail : String<br>}</pre><h4>ActiveIndicatorView</h4><pre>import SwiftUI</pre><pre>struct ActiveIndicatorView: UIViewRepresentable {  //製作UIKIT物件<br>    func makeUIView(context: Context) -&gt; UIActivityIndicatorView {<br>        let aiv = UIActivityIndicatorView(style: .large)<br>        aiv.startAnimating()<br>        aiv.color = UIColor.white<br>        return aiv<br>    }<br>    <br>    func updateUIView(_ uiView: UIActivityIndicatorView, context: Context) {<br>    }<br>   <br>    typealias UIViewType = UIActivityIndicatorView<br>    <br>    <br>}</pre><pre>struct ActiveIndicatorView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ActiveIndicatorView()<br>    }<br>}</pre><h4>CategoryDetialView</h4><pre>import SwiftUI</pre><pre>import SDWebImageSwiftUI</pre><pre>class CaregoryDetialViewModle: ObservableObject {<br>    <br>    @Published var isLoading = true///宣告isLoading 狀態 預設為true<br>    @Published var arts = [AirTableRecord]()<br>    @Published var errorMesage = &quot;&quot;<br>    init(){<br>        <br>        <br>    <br>    DispatchQueue.main.asyncAfter(deadline: .now() + 2){<br>       <br>        self.isLoading = false<br>        guard let url = URL(string: &quot;&lt;https://api.airtable.com/v0/appUJv9kyMlHpugJ7/Art&gt;&quot;) else {<br>            return<br>        }<br>        <br>        var request = URLRequest(url: url)<br>        request.setValue(&quot;AirTable授權碼&quot;, forHTTPHeaderField: &quot;Authorization&quot;)<br>        request.httpMethod = &quot;GET&quot;<br>        URLSession.shared.dataTask(with: request) { data, resp, err in<br>            <br>            guard let data = data else { return }<br>            do{<br>                let reords = try JSONDecoder().decode(AirtableRecords.self, from: data)<br>                self.arts = reords.records<br>            }<br>            catch{<br>                <br>                print(&quot;Failed to decode JSON&quot;,error)<br>                self.errorMesage = error.localizedDescription<br>            }<br>        }.resume()</pre><pre>}<br>        <br>    }<br>    <br>}</pre><pre>struct CategoryDetialView: View {<br>    <br>    @ObservedObject var vm = CaregoryDetialViewModle() /// 宣告VM<br>    <br>    var body: some View{<br>            <br>            if vm.isLoading == true{<br>                VStack{<br>                    ActiveIndicatorView()<br>                    Text(&quot;loading&quot;)<br>                        .font(.system(size: 12, weight: .semibold))<br>                        .foregroundColor(.white)<br>                }<br>                .padding()<br>                .background(Color.black)<br>                .cornerRadius(6)<br>               <br>            }else{<br>                <br>                ZStack{<br>                    Text(vm.errorMesage)<br>                    ScrollView(.vertical){<br>                        VStack(spacing: 12){<br>                            ForEach(vm.arts, id: \\.self) { art in<br>                            VStack{<br>                              WebImage(url: URL(string: art.fields.thumbnail))<br>                                    .resizable()<br>                                    .scaledToFill()<br>                                    .clipped()<br>                                    .frame(height: 200)<br>                                <br>                                HStack{<br>                                    Text(art.fields.name)<br>                                    .font(.system(size: 14, weight: .semibold))<br>                                Spacer()<br>                                }<br>                                .padding()<br>                                .background(Color.white)<br>                                <br>                            }<br>                           <br>                            .asTile()<br>                        }<br>                    }.padding(.horizontal)<br>                        .padding(.top)<br>                    <br>                    }<br>                }<br>          .navigationBarTitle(&quot;Category&quot;, displayMode: .inline)<br>            }<br>        <br>    }<br>}</pre><pre>struct CategoryDetialView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        NavigationView{<br>        CategoryDetialView()<br>    }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c51dc7fd5305" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【App Dev-SwiftUI心得筆記】#2 切換頁面與模擬Loading資料]]></title>
            <link>https://medium.com/elio-iosapp/app-dev-swiftui%E5%BF%83%E5%BE%97%E7%AD%86%E8%A8%98-2-%E5%88%87%E6%8F%9B%E9%A0%81%E9%9D%A2%E8%88%87%E6%A8%A1%E6%93%ACloading%E8%B3%87%E6%96%99-55526cc95ef8?source=rss-a4d0bfa86011------2</link>
            <guid isPermaLink="false">https://medium.com/p/55526cc95ef8</guid>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Elio Shih]]></dc:creator>
            <pubDate>Sun, 16 May 2021 15:58:33 GMT</pubDate>
            <atom:updated>2021-11-29T07:20:10.084Z</atom:updated>
            <content:encoded><![CDATA[<p>承上次初次用SwiftUI切版,這次Code越來越上手了 😎</p><p>這是的目標是將首頁的畫面弄的更完整,並且新增CategoryDetail頁面 ：Ｄ</p><h4>將首頁畫面豐富&amp;完整化</h4><h4>Components Used:</h4><p>Zstack, Color(literal), LineGradient,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*xg9Srjb0YefEVZOVfS5SAg.png" /></figure><p>利用Zstack做出前後圖層，在底圖上用LineGradient、Color(literal)直接玄取顏色製作漸層背景</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e5076b6e0a82ecf07b3ef6c5990b356/href">https://medium.com/media/5e5076b6e0a82ecf07b3ef6c5990b356/href</a></iframe><p>將 PopularRestaurantsView、TrendingCreators 畫面補齊</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bac05193f7bb29f39a8a0bd56df17af2/href">https://medium.com/media/bac05193f7bb29f39a8a0bd56df17af2/href</a></iframe><h3>CleanCode 時間</h3><p>將Code分類建立成獨立檔案放入不同的資料夾內</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*XGAfR_OeQExgTrF6OLUlrA.png" /></figure><blockquote>可以運用 PreviewProvider 建立兩個模擬器 (獨立檔案的View ＆ 整體的View)</blockquote><pre>struct PopularDestinationsView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        PopularDestinationsView()<br>        DiscoverView()<br>    }<br>}</pre><blockquote>用 ViewModifier 建立管理重複的樣式</blockquote><pre>extension View{<br>    func asTile() -&gt; some View{<br>        modifier(TileModifier())<br>    }<br>}<br><br>struct TileModifier: ViewModifier {<br>    func body(content: Content) -&gt; some View {<br>        content<br>            .background(Color(.white))<br>            .cornerRadius(10)<br>            .shadow(color: .gray, radius: 3, x: 0, y: 2)<br>    }<br>}</pre><h3>製作CategoryDetail 畫面</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*G7YoE2z3bmD6pBL7s_5C7A.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71c999a11e43eb862ff1e3b0f990c140/href">https://medium.com/media/71c999a11e43eb862ff1e3b0f990c140/href</a></iframe><h3>使用NavigationLink 連接畫面</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*Ox7QUYCZK_LaodK0hYnlJA.gif" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/207a5ae62a9d61f2b29c9a13ef337dea/href">https://medium.com/media/207a5ae62a9d61f2b29c9a13ef337dea/href</a></iframe><h3>製作Loading頁面</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*g-jjqP8BcI9mERZFSCAz7w.gif" /></figure><h4>用DispatchQueue.main.asyncAfter 來模擬loading時間</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbb50db555c3c9620b8b80aac277e2da/href">https://medium.com/media/fbb50db555c3c9620b8b80aac277e2da/href</a></iframe><h4>新增讀取畫面元件</h4><p>使用ActiveIndicatorView</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37728ef4e4d3fc760af8c2da410bcb52/href">https://medium.com/media/37728ef4e4d3fc760af8c2da410bcb52/href</a></iframe><h4>加入畫面中</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb70696e9bb517b7c938ef483e2a0e90/href">https://medium.com/media/eb70696e9bb517b7c938ef483e2a0e90/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55526cc95ef8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elio-iosapp/app-dev-swiftui%E5%BF%83%E5%BE%97%E7%AD%86%E8%A8%98-2-%E5%88%87%E6%8F%9B%E9%A0%81%E9%9D%A2%E8%88%87%E6%A8%A1%E6%93%ACloading%E8%B3%87%E6%96%99-55526cc95ef8">【App Dev-SwiftUI心得筆記】#2 切換頁面與模擬Loading資料</a> was originally published in <a href="https://medium.com/elio-iosapp">iOS 雛鳥學飛之路</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【App Dev-SwiftUI心得筆記】#1 切版初體驗]]></title>
            <link>https://medium.com/elio-iosapp/app-dev-swiftui%E5%BF%83%E5%BE%97%E7%AD%86%E8%A8%98-1-%E5%88%87%E7%89%88%E5%88%9D%E9%AB%94%E9%A9%97-e6052ea2d6f7?source=rss-a4d0bfa86011------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6052ea2d6f7</guid>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Elio Shih]]></dc:creator>
            <pubDate>Sat, 08 May 2021 19:36:48 GMT</pubDate>
            <atom:updated>2021-11-29T07:13:02.491Z</atom:updated>
            <content:encoded><![CDATA[<p>之前寫 iOS 的畫面都是用StoryBoard來寫,這次來試試看用SwiftUI來寫寫看 🤨</p><p>這次要來挑戰看看用SwiftUI 寫一個介紹台灣的APP “Discover Taiwan”</p><p>對SwiftUI不熟悉的我呢,只好找資源幫忙拉！</p><p>這次透過 LBTA 的課程 <strong><em>Travel Discovery</em></strong> 來學習 swiftUI ,並配上<strong><em> 快速精通SwiftUI </em></strong>作為字典書 🤓</p><h3>Components Used :</h3><p>Navigation View, ScrollView, VStack, HStack, Text, Spacer , ForEach, Image,</p><h4>建構出WireFrame:</h4><p>運用 Spacer() 來建構出各個物件的位置</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2d80f3f48f8193913da155454784b1c/href">https://medium.com/media/e2d80f3f48f8193913da155454784b1c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*fh4wfV2Vm1zep3nl7_5hrQ.png" /></figure><blockquote>小技巧：將程式碼轉成元件Component</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wf34sgVBvk7Kkw1LQzc7gA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lKH-4T074sMAfbsAUxWodA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vp3qJOhLLCVZ6dFDLn88BQ.png" /></figure><h4>開始建構物件內容</h4><ol><li>透過 陣列的方式 進行模組化物件,並且運用 SF Symbols 2 作為小ICON</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7e523ed701da9d4cb470e31890887c2/href">https://medium.com/media/e7e523ed701da9d4cb470e31890887c2/href</a></iframe><p>2. 透過 .resizable .scaledToFill 製作照片卡</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63b15642888fb646b579919971988bac/href">https://medium.com/media/63b15642888fb646b579919971988bac/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*-hhoBQks3WWqzcvQwSrJ9w.png" /><figcaption>照片卡來源：【Taiwan Scenery Gallery】</figcaption></figure><h4>心得：</h4><p>發現 SwiftUI 比 StoryBoard 在建構畫面時快很多,摳起來很像在寫 html :P<br>而且還能即時預覽畫面,真的比較方便很多,能夠馬上做微調。看來真的要多練練這項技能了 ^ 3 ^</p><h3>學習資料Note：</h3><h4>SF Symbols 2</h4><p>Apple 系統內建 Symbols 總覽</p><p><a href="https://developer.apple.com/sf-symbols/">https://developer.apple.com/sf-symbols/</a></p><h4>Taiwan Scenery Gallery</h4><p>在網路上找到的一個專門分享台灣地方照片的平台,概念真的很棒。</p><p>這也是我想要做 Discover Taiwan APP 的原因之一， 想要效仿他們一樣，到處去收集拍照 台灣的美 :D 並且做成 APP。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6052ea2d6f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elio-iosapp/app-dev-swiftui%E5%BF%83%E5%BE%97%E7%AD%86%E8%A8%98-1-%E5%88%87%E7%89%88%E5%88%9D%E9%AB%94%E9%A9%97-e6052ea2d6f7">【App Dev-SwiftUI心得筆記】#1 切版初體驗</a> was originally published in <a href="https://medium.com/elio-iosapp">iOS 雛鳥學飛之路</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>