资本化第一句话(斯威夫特)

前端之家收集整理的这篇文章主要介绍了资本化第一句话(斯威夫特)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个字符串描述来保存我的句子.我只想把第一个字母大写.我尝试了不同的东西,但大多数都给了我例外和错误.我正在使用 Xcode 6.

这是我到目前为止所尝试的

let cap = [description.substringToIndex(advance(0,1))] as String
    description = cap.uppercaseString + description.substringFromIndex(1)

它给了我:类型’String.Index’不符合协议’IntegerLiteralConvertible’

我试过了

func capitalizedStringWithLocale(locale:0) -> String

但我无法弄清楚如何让它发挥作用.
有任何想法吗?

import Foundation

// A lowercase string
let description = "the quick brown fox jumps over the lazy dog."

// The start index is the first letter
let first = description.startIndex

// The rest of the string goes from the position after the first letter
// to the end.
let rest = advance(first,1)..<description.endIndex

// Glue these two ranges together,with the first uppercased,and you'll
// get the result you want. Note that I'm using description[first...first]
// to get the first letter because I want a String,not a Character,which
// is what you'd get with description[first].
let capitalised = description[first...first].uppercaseString + description[rest]

// Result: "The quick brown fox jumps over the lazy dog."

您可能希望确保在开始之前句子中至少有一个字符,否则您将在尝试将索引超出字符串末尾时遇到运行时错误.

原文链接:https://www.f2er.com/swift/318969.html

猜你在找的Swift相关文章