将String.CharacterView.Index转换为int

时间:2016-02-17 18:54:15

标签: swift

如何将titleRange转换为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 个答案:

答案 0 :(得分:-1)

我不确定,但我认为你不能在Int中转换String.Index,所以唯一的方法是将它转换为String,然后转换为Int。

你可以建立一个像:

这样的扩展程序
extension String.Index {
    func toInt() -> Int {
        if let str:String = String(self) {
            return Int(str)!
        }
        return 0
    }
}

将此代码插入到.swift文件或随时存储扩展名的位置。