Swift3.0語言教程字符串與URL的數據轉換與自由轉換,字符串中的字符永久保存除了能夠保存在文件中外,還能夠保存到URL中,保存到URL中能夠不用浪費設備的空間,固然也能夠將URL中的內容讀取出來,並轉換爲字符串。首先咱們來看如何將字符串中的字符寫入到URL中,要想實現此功能,須要使用到NSString中的write(to:atomically:encoding:)方法,其語法形式以下:html
func write(to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throwsapp
其中,參數說明以下:ui
【示例1-102】如下將字符串的字符寫入到URL中。編碼
import Foundationatom
var str=NSString(string:"One is always on a strange road, watching strange scenery and listening to strange music. Then one day, you will find that the things you try hard to forget are already gone. ")url
var path="/Users/mac/Desktop/File"spa
var url=URL(fileURLWithPath:path)orm
//寫入htm
do{blog
try str.write(to: url, atomically: true, encoding: String.Encoding.ascii.rawValue)
}catch{
}
運行效果如圖1.5所示。
圖1.5 運行效果
NSString能夠將字符保存到URL中,還能夠將URL中的內容讀取出來,並轉換爲字符串,其此時須要使用到NSString中的init(contentsOf:encoding:)方法,其語法形式以下:
convenience init(contentsOf url: URL, encoding enc: UInt) throws
其中,url用來指定URL,enc用來指定編碼格式。
【示例1-103】如下將讀取URL中的內容。
import Foundation
var url=URL(string:"http://www.baidu.com")
var str:NSString?=nil
//讀取內容
do{
str=try NSString(contentsOf: url!,encoding: String.Encoding.ascii.rawValue)
}catch{
}
print(str!)
運行結果以下:
<html>
<head>
<script>
location.replace(location.href.replace("https://","http://"));
</script>
</head>
<body>
<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
</body>
</html>
在此代碼中url指定的"http://www.baidu.com中的內容。
在上文中咱們提到的轉換都是針對英文進行的常見轉換,可是若是咱們想要將簡體中文轉爲轉換爲拉丁字符,或者是其餘,使用上文中提到的轉換是不可行的,在NSString中提供了一個applyingTransform(_:reverse:)方法,爲咱們解決了這一問題,它能夠實現自由轉換的功能,其語法形式以下:
func applyingTransform(_ transform: StringTransform, reverse: Bool) -> String?
其中,transform用來設置指定一個StringTransform常量,reverse用來設置字符串是否可逆。
【示例1-104】如下將簡體中文漢字轉碼成拉丁字母中的漢語拼音表示。
import Foundation
let shanghai="上海"
print(shanghai.applyingTransform(StringTransform.toLatin, reverse: false)!) //轉換
運行結果以下:
shàng hǎi