将ObjectiveO c中的rangeOfString转换为Swift

时间:2015-06-23 18:44:45

标签: ios objective-c swift nsrange

我试着翻译这段短代码几个小时。 目标C:

NSString *urlStr = [request.URL absoluteString];
NSArray *urlParts = [urlStr componentsSeparatedByString:[NSString stringWithFormat:@"%@/", kREDIRECTURI]];

if (urlParts.count > 1)
{
    urlStr = urlParts[1];
    NSRange token = [urlStr rangeOfString:@"#access_token="];

    if (token.location != NSNotFound)
    {
        vc.access_token = [urlStr substringFromIndex:NSMaxRange(token)];
    }
}

我尝试了什么:

斯威夫特:

var urlParts : NSArray = urlStr!.componentsSeparatedByString("\(kREDIRECTURI)")
if urlParts.count > 1
{
    urlStr = urlParts[1] as? String
    var token  = urlStr!.rangeOfString("#access_token=", options: NSStringCompareOptions.allZeros) as NSRange!

    if token != nil
    {
         var vc = ViewController()
         urlStr!.substringFromIndex(NSMaxRange(token))!
    }
}

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我将假设access_token查询参数位于结尾,代码跟随字符串,如'http:\ ...#access_token =',url以结尾处的代码结束。这是一个简单的方法,可以从网址中提取代码,

String text = "This "+  "\r\n"+ "Must"+ "\r\n"+ "Work!!!" +"\r\n";

对于早期版本的Swift,你可以使用if patter来解包可选的

func getTokenFromUrl(url: String) -> String? {

    let range1 = url.rangeOfString("#access_token")

    guard let range = range1 else { return nil }

    let startIndex = range.endIndex.successor()
    let rangeOfToken = url.endIndex

    let rangeOfString = startIndex ..< rangeOfToken

   return  url.substringWithRange(rangeOfString)
}

let url1 = "http://stackoverflow.com/questions/31010975/translate-rangeofstring-from-objective-c-to-swift?#access_token=873jasf82jmsa8sd"

let url2 = "http://stackoverflow.com/questions/31010975/translate-rangeofstring-from-objective-c-to-swift"

getTokenFromUrl(url1) // returns 873jasf82jmsa8sd
getTokenFromUrl(url2) // returns nil