popeyelau / wiki

📒Wiki for many useful notes, source, commands and snippets.
2 stars 0 forks source link

Swift 泛型命名空间 #4

Open popeyelau opened 5 years ago

popeyelau commented 5 years ago

import Foundation
import CommonCrypto

protocol Compatible { }

struct Wrapper<Base> {
    let base: Base
    init(_ base: Base) {
        self.base = base
    }
}

extension Compatible {
    var pp: Wrapper<Self> {
        get { return Wrapper(self) }
        set { }
    }
}

extension String: Compatible {}

extension Wrapper where Base == String {
    var md5: String {
        guard let data = base.data(using: .utf8) else {
            return base
        }
        var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
        _ = data.withUnsafeBytes { bytes in
            return CC_MD5(bytes, CC_LONG(data.count), &digest)
        }
        return digest.map { String(format: "%02x", $0) }.joined()
    }
}
// 调用时,使用 xxx.pp.xxx
"Hello".pp.md5 // "8b1a9953c4611296a827abf8c47804d7"