2016-02-17 53 views
1

如何將titleRange轉換爲Int!?將String.CharacterView.Index轉換爲int

var text: String = "Another neat aspect of playgrounds and the Assistant Editor is that you can inspect the output at different points in the program 
flow. So for instance, you could add another view of the UILable to the 
Assistant Editor before you’ve applied the changes to background color and 
corner radius to see what it looks like before that. Just click on the little white circle next to the 「UILabel」 to the right of the line where you’d like to inspect. " 


let titleRange = Int(text.characters.indexOf(".")) //Convert to Int! 

var attributedText: NSMutableAttributedString = NSMutableAttributedString(string: text as String) 
attributedText.addAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(20)], range: NSRange(location: 0, length: titleRange)) 

回答

-1

我不知道,但我認爲你不能轉換String.Index的詮釋,所以唯一的辦法是將其轉換爲字符串,並詮釋了。

你可以建立一個擴展,如:

extension String.Index { 
    func toInt() -> Int { 
     if let str:String = String(self) { 
      return Int(str)! 
     } 
     return 0 
    } 
} 

插入這段代碼放到存儲在.swift文件或當你想你的擴展。