我正在尝试转换十六进制值的表情符号,我找到了一些在线代码来实现它,但它只是使用目标C,如何对Swift做同样的工作呢?
发布于 2014-12-03 17:31:20
这是一种“纯Swift”方法,无需使用Foundation:
let smiley = ""
let uni = smiley.unicodeScalars // Unicode scalar values of the string
let unicode = uni[uni.startIndex].value // First element as an UInt32
print(String(unicode, radix: 16, uppercase: true))
// Output: 1F60A
请注意,Swift Character
表示一个"Unicode字素集群“(比较Swift博客中的Swift 2中的字符串 ),它可以由几个"Unicode标量值”组成。下面是@TomSawyer的评论中的例子:
let zero = "0️⃣"
let uni = zero.unicodeScalars // Unicode scalar values of the string
let unicodes = uni.map { $0.value }
print(unicodes.map { String($0, radix: 16, uppercase: true) } )
// Output: ["30", "FE0F", "20E3"]
发布于 2019-03-07 07:55:17
如果有人试图找到一种将Emoji转换为Unicode字符串的方法
extension String {
func decode() -> String {
let data = self.data(using: .utf8)!
return String(data: data, encoding: .nonLossyASCII) ?? self
}
func encode() -> String {
let data = self.data(using: .nonLossyASCII, allowLossyConversion: true)!
return String(data: data, encoding: .utf8)!
}
}
示例:
结果: \ud83d\ude0d
结果:
发布于 2014-12-03 17:23:10
它的工作原理类似,但在打印时要注意:
import Foundation
var smiley = ""
var data: NSData = smiley.dataUsingEncoding(NSUTF32LittleEndianStringEncoding, allowLossyConversion: false)!
var unicode:UInt32 = UInt32()
data.getBytes(&unicode)
// println(unicode) // Prints the decimal value
println(NSString(format:"%2X", unicode)) // Print the hex value of the smiley
https://stackoverflow.com/questions/27277856
复制相似问题