swift中的个别特殊实现

记录开发中遇到的一些语法上的差异点

Posted by Lgn on July 4, 2018

最近临时转做app开发了,采用了swift语言开发,这里简要记录几点开发过程中遇到的难点

  • 1.函数做参数和变量
//返回值无参
var callback : (() -> Void)?

//闭包默认是不可逃逸的,逃逸闭包需要像这样被标记@escaping
func setData(call: @escaping () -> Void)
{
    callback = call
}

//带参返回
var callback: ((String) -> Int)?
    
func setData(call: @escaping (String) -> Int)
{
    callback = call
}
  • 2.回调js时参数有xml内容的情况
let fileUrl:URL = URL(fileURLWithPath: path)
do {
    var content:String = try String(contentsOf: fileUrl, encoding: .utf8)
    print(content)
    
    //xml要去掉换行符,否则会报EOF的语法错误
    content = content.trimmingCharacters(in: .whitespacesAndNewlines)
    content = content.replacingOccurrences(of: "\r", with: "")
    // \\n --> json中不能有换行符
    content = content.replacingOccurrences(of: "\n", with: "")
    content = content.replacingOccurrences(of: "\'", with: "\\\'")
    content = content.replacingOccurrences(of: "\"", with: "\\\'")
    
    //json字符串
    let reVal:String = "{\"name\":\"\(fileUrl.lastPathComponent)\", \"content\":\"\(content)\"}"
    let jsStr = "resolvePromise('\(promiseId)','\(reVal)','')"
    
    webView.evaluateJavaScript(jsStr) { (any, error) in
        if(error != nil)
        {
            print(error!)
        }
    }
    
} catch {
    print("read file error at", path)
}

对应上面读取的xml传给js时报的错误:

//json的key和value要用引号包含
Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=SyntaxError: Unexpected token '<', WKJavaScriptExceptionColumnNumber=0, WKJavaScriptExceptionSourceURL=http://xxxxxxxxxx, NSLocalizedDescription=A JavaScript exception occurred}

//不能有换行符
WKJavaScriptExceptionMessage=SyntaxError: Unexpected EOF