简体   繁体   English

<I>迅速</i>将字符串转换为范围<I>错误</i>

[英]String is not convertible to Range<I> error on swift anyone

 func setupAvatarColor(name: String, incoming: Bool) {
        let diameter = incoming ? UInt(collectionView.collectionViewLayout.incomingAvatarViewSize.width) : UInt(collectionView.collectionViewLayout.outgoingAvatarViewSize.width)

        let rgbValue = name.hash
        let r = CGFloat(Float((rgbValue & 0xFF0000) >> 16)/255.0)
        let g = CGFloat(Float((rgbValue & 0xFF00) >> 8)/255.0)
        let b = CGFloat(Float(rgbValue & 0xFF)/255.0)
        let color = UIColor(red: r, green: g, blue: b, alpha: 0.5)

        **let nameLength = count(name);**
        let initials : String? = name.substringToIndex(advance(sender.startIndex, min(3, nameLength)))
        let userImage = JSQMessagesAvatarFactory.avatarWithUserInitials(initials, backgroundColor: color, textColor: UIColor.blackColor(), font: UIFont.systemFontOfSize(CGFloat(13)), diameter: diameter)

        avatars[name] = userImage
    }


I receiving the error '`String is not convertible to Range<I>'in the highlighted code (10th line)`. AnyOne?

In Swift 2 Apple removed alot of global functions. 在Swift 2中,Apple删除了很多全局功能。

In your case to get the length of a String do: 在您的情况下,要获取字符串的长度,请执行以下操作:

str.characters.count

You can't use count anymore in Swift 2.0 for getting the string length. 在Swift 2.0中,您不能再使用count来获取字符串长度。

So instead of: 所以代替:

let nameLength = count(name);

Use: 采用:

let nameLength = name.endIndex;

or 要么

let nameLength = name.characters.count;

Swift 2.0 lets you call advance on endIndex and startIndex which is what you need here I guess. Swift 2.0允许您在endIndex和startIndex上调用Advance,这是您在这里需要的。 Ps, avataWithUserInitials takes NSString as first argument and substringToIndex returns String so I don't see any reason to define it as String optional. ps,avataWithUserInitials将NSString作为第一个参数,substringToIndex返回String,所以我看不出有任何理由将其定义为String可选。

let initials = name.substringToIndex((name.characters.count < 3) ? name.endIndex:name.startIndex.advancedBy(3))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM