Swift 入門指南 V1.00 - 單元 24 - 整合 Encrypt
- Get link
- X
- Other Apps

Swift 入門指南 V1.00 - 單元 24 - 整合 Encrypt

要在 EncryptorMacOS 專案 (project) 中使用 Encrypt 類別 (class) 的功能,就得把 Encrypt 類別加入到專案之中,此時從導覽列 EncryptorMacOS 的圖示上顯示快顯功能表,點擊 Add Files to "EncryptorMacOS" 的指令

然後從 EncryptCommandLine 專案選擇 Encrypt.swift ,最後點擊右下角的〔Add〕

這樣 Encrypt 類別就加入到 EncryptorMacOS 中了

我們現在開始實際建置編碼、解碼的功能,先加入三個屬性 (property) ,分別是選擇型態 (optionals) Encrypt 的 e 以及暫存輸入字串 (string) 的 inputText 與輸入字串的 outputText

e 用選擇型態的原因很簡單,因為 e 選擇型態的屬性會被初始化成 nil ,當使用者按下 New 按鈕的時候才會真正建立 Encrypt 屬性 e ,因此下面 newMethod() 就是用 Encrypt 的建構子 (initializer) 建立 e ,最後判斷 e 不是 nil 的話,就印出 code 的 description ,也就是 code 的字串形式。
判斷 e 是否為 nil 是選擇型態的慣例寫法,至於編碼方法 encodeMethod() 與解碼方法 decodeMethod() 的實作如下

首先從 input 的 stringValue 取得文字,然後把文字用 inputText 暫存,接著判斷 inputText 是否為空字串 (empty string) ,這是因為如果 inputText 是空字串的話,就表示使用者沒有輸入,編碼或解碼也就沒有意義,所以如果是空字串就打住直接印出提示訊息。
如果不是空字串,就表示有文字可進行編碼或解碼,接下來便是判斷 e 是否為 nil ,如果 e 是 nil 的話,就表示使用者還沒按 New 按鈕,那也沒辦法進行編碼或解碼,因此 e 不是 nil 才進行編碼或解碼。
上面可以看到 encodeMethod() 跟 decodeMethod() 的設計大體相同,除了前者呼叫 e 的 toEncode() ,後者則是呼叫 e 的 toDecode() 之外。
好了,來測試看看囉,按執行鍵後先點擊 Encode

還沒輸入,下面輸入 There is no spoon. ,然後再點擊 Encode

也還沒按 New ,點擊 New

編碼結果如下

解碼結果如下

Encode 跟 Decode 兩個按鈕實作完成,下一個單元繼續實作 Save 與 Load 按鈕。
中英文術語對照
專案 | project |
類別 | class |
屬性 | property |
選擇型態 | optionals |
字串 | string |
建構子 | initializer |
空字串 | empty string |
訂閱:
張貼留言 (Atom)
window.___gcfg = { 'lang': 'zh-TW' };
- Get link
- X
- Other Apps
沒有留言:
張貼留言