我需要创建一个字符串的格式,可以转换Int, Int64,双精度等类型为字符串。使用Objective-C,我可以通过:

NSString *str = [NSString stringWithFormat:@"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE, STRING_VALUE];

如何做同样的,但在Swift?


当前回答

我认为两者都有

let str = String(format:"%d, %f, %ld", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE)

and

let str = "\(INT_VALUE), \(FLOAT_VALUE), \(DOUBLE_VALUE)"

都是可接受的,因为用户询问格式,这两种情况都符合他们的要求:

我需要创建一个字符串的格式,可以转换int, long, double等类型的字符串。

显然,前者可以比后者更好地控制格式,但这并不意味着后者不是一个可接受的答案。

其他回答

有一个简单的解决方案,我学会了“我们<3 Swift”,如果你既不能导入基础,使用round()和/或不想要字符串:

var number = 31.726354765
var intNumber = Int(number * 1000.0)
var roundedNumber = Double(intNumber) / 1000.0

结果:31.726

我知道自从这篇文章发表以来已经过去了很多时间,但我也遇到过类似的情况,所以创建了一个simples类来简化我的生活。

public struct StringMaskFormatter {

    public var pattern              : String    = ""
    public var replecementChar      : Character = "*"
    public var allowNumbers         : Bool      = true
    public var allowText            : Bool      = false


    public init(pattern:String, replecementChar:Character="*", allowNumbers:Bool=true, allowText:Bool=true)
    {
        self.pattern            = pattern
        self.replecementChar    = replecementChar
        self.allowNumbers       = allowNumbers
        self.allowText          = allowText
    }


    private func prepareString(string:String) -> String {

        var charSet : NSCharacterSet!

        if allowText && allowNumbers {
            charSet = NSCharacterSet.alphanumericCharacterSet().invertedSet
        }
        else if allowText {
            charSet = NSCharacterSet.letterCharacterSet().invertedSet
        }
        else if allowNumbers {
            charSet = NSCharacterSet.decimalDigitCharacterSet().invertedSet
        }

        let result = string.componentsSeparatedByCharactersInSet(charSet)
        return result.joinWithSeparator("")
    }

    public func createFormattedStringFrom(text:String) -> String
    {
        var resultString = ""
        if text.characters.count > 0 && pattern.characters.count > 0
        {

            var finalText   = ""
            var stop        = false
            let tempString  = prepareString(text)

            var formatIndex = pattern.startIndex
            var tempIndex   = tempString.startIndex

            while !stop
            {
                let formattingPatternRange = formatIndex ..< formatIndex.advancedBy(1)

                if pattern.substringWithRange(formattingPatternRange) != String(replecementChar) {
                    finalText = finalText.stringByAppendingString(pattern.substringWithRange(formattingPatternRange))
                }
                else if tempString.characters.count > 0 {
                    let pureStringRange = tempIndex ..< tempIndex.advancedBy(1)
                    finalText = finalText.stringByAppendingString(tempString.substringWithRange(pureStringRange))
                    tempIndex = tempIndex.advancedBy(1)
                }

                formatIndex = formatIndex.advancedBy(1)

                if formatIndex >= pattern.endIndex || tempIndex >= tempString.endIndex {
                    stop = true
                }

                resultString = finalText

            }
        }

        return resultString
    }

}

以下链接发送到完整的源代码: https://gist.github.com/dedeexe/d9a43894081317e7c418b96d1d081b25

该解决方案基于本文: http://vojtastavik.com/2015/03/29/real-time-formatting-in-uitextfield-swift-basics/

成功尝试一下:

 var letters:NSString = "abcdefghijkl"
        var strRendom = NSMutableString.stringWithCapacity(strlength)
        for var i=0; i<strlength; i++ {
            let rndString = Int(arc4random() % 12)
            //let strlk = NSString(format: <#NSString#>, <#CVarArg[]#>)
            let strlk = NSString(format: "%c", letters.characterAtIndex(rndString))
            strRendom.appendString(String(strlk))
        }

没有什么特别的

let str = NSString(format:"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, LONG_VALUE, STRING_VALUE)
let INT_VALUE=80
let FLOAT_VALUE:Double= 80.9999
let doubleValue=65.0
let DOUBLE_VALUE:Double= 65.56
let STRING_VALUE="Hello"

let str = NSString(format:"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE, STRING_VALUE);
 println(str);