在objective-c它看起来像这样:
#include <sys/xattr.h> @implementation NSString (reverse) -(NSString*)sha1 { NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding]; uint8_t digest[CC_SHA1_DIGEST_LENGTH]; CC_SHA1(data.bytes,(int)data.length,digest); NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2]; for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) [output appendFormat:@"%02x",digest[i]]; return output; } @end
我需要像这样的Swift,是可能吗?
请,显示工作示例。
您的Objective-C代码(使用NSString类别)可以直接转换为Swift
(使用String扩展)。
原文链接:https://www.f2er.com/swift/320782.html(使用String扩展)。
首先你必须创建一个“桥接头”并添加
#import <CommonCrypto/CommonCrypto.h>
然后:
extension String { func sha1() -> String { let data = self.dataUsingEncoding(NSUTF8StringEncoding)! var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH),repeatedValue: 0) CC_SHA1(data.bytes,CC_LONG(data.length),&digest) let output = NSMutableString(capacity: Int(CC_SHA1_DIGEST_LENGTH)) for byte in digest { output.appendFormat("%02x",byte) } return output as String } } println("Hello World".sha1())
这可以写得稍短,Swifter as
extension String { func sha1() -> String { let data = self.dataUsingEncoding(NSUTF8StringEncoding)! var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH),&digest) let hexBytes = map(digest) { String(format: "%02hhx",$0) } return "".join(hexBytes) } }
Swift 2的更新:
extension String { func sha1() -> String { let data = self.dataUsingEncoding(NSUTF8StringEncoding)! var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH),&digest) let hexBytes = digest.map { String(format: "%02hhx",$0) } return hexBytes.joinWithSeparator("") } }
Swift 3的更新:
extension String { func sha1() -> String { let data = self.data(using: String.Encoding.utf8)! var digest = [UInt8](repeating: 0,count:Int(CC_SHA1_DIGEST_LENGTH)) data.withUnsafeBytes { _ = CC_SHA1($0,CC_LONG(data.count),&digest) } let hexBytes = digest.map { String(format: "%02hhx",$0) } return hexBytes.joined() } }