在Swift中将Int转换为String

时间:2014-06-11 11:05:26

标签: string casting int converter swift

我正在尝试研究如何在Swift中将Int投射到String

我使用NSNumber找出了解决方法,但我很想知道如何在Swift中完成所有工作。

let x : Int = 45
let xNSNumber = x as NSNumber
let xString : String = xNSNumber.stringValue

24 个答案:

答案 0 :(得分:889)

Int转换为String

let x : Int = 42
var myString = String(x)

反过来 - 将String转换为Int

let myString : String = "42"
let x: Int? = myString.toInt()

if (x != nil) {
    // Successfully converted String to Int
}

或者如果您使用的是Swift 2或3:

let x: Int? = Int(myString)

答案 1 :(得分:88)

检查以下答案:

let x : Int = 45
var stringValue = "\(x)"
print(stringValue)

答案 2 :(得分:56)

在Swift 3.0中

var value: Int = 10
var string = String(describing: value)

答案 3 :(得分:53)

以下是4种方法:

var x = 34
var s = String(x)
var ss = "\(x)"
var sss = toString(x)
var ssss = x.description

我可以想象有些人会遇到ss的问题。但是如果你想构建一个包含其他内容的字符串,那么为什么不呢。

答案 4 :(得分:25)

为了完整起见,您还可以使用:

let x = 10.description

或支持描述的任何其他值。

答案 5 :(得分:25)

Swift 4

let x:Int = 45
let str:String = String(describing: x)

Developer.Apple.com > String > init(describing:)

  

String(描述:)初始化程序是将任何类型的实例转换为字符串的首选方法。

Custom String Convertible

enter image description here

答案 6 :(得分:10)

Swift 4:

尝试在没有可选()字的情况下显示标签中的值。

这里x是使用。的值。

let str:String = String(x ?? 0)

答案 7 :(得分:8)

为了节省您自己的时间和麻烦,您可以进行Int扩展。通常我会创建一个共享代码文件,我在其中放置扩展,枚举和其他有趣的东西。这是扩展代码的样子:

extension Int
{
    func toString() -> String
    {
        var myString = String(self)
        return myString
    }
}

然后,当你想将int转换为字符串时,你可以执行以下操作:

var myNumber = 0
var myNumberAsString = myNumber.toString()

答案 8 :(得分:7)

swift 3.0 中,我们可以将Int转换为StringString转换为Int

//convert Integer to String in Swift 3.0

let theIntegerValue :Int = 123  // this can be var also
let theStringValue :String = String(theIntegerValue)


//convert String to Integere in Swift 3.0


let stringValue : String = "123"
let integerValue : Int = Int(stringValue)!

答案 9 :(得分:7)

无论出于何种原因,接受的答案对我都不起作用。我采用了这种方法:

var myInt:Int = 10
var myString:String = toString(myInt)

答案 10 :(得分:5)

多种方法:

var str1:String="\(23)"
var str2:String=String(format:"%d",234)

答案 11 :(得分:4)

斯威夫特2:

#ifndef PubSubClient_h
#define PubSubClient_h

#include <Arduino.h>
#include "Client.h"

// MQTT_MAX_PACKET_SIZE : Maximum packet size
#define MQTT_MAX_PACKET_SIZE 128

// MQTT_KEEPALIVE : keepAlive interval in Seconds
#define MQTT_KEEPALIVE 15

#define MQTTPROTOCOLVERSION 3
#define MQTTCONNECT     1 << 4  // Client request to connect to Server
#define MQTTCONNACK     2 << 4  // Connect Acknowledgment
#define MQTTPUBLISH     3 << 4  // Publish message
#define MQTTPUBACK      4 << 4  // Publish Acknowledgment
#define MQTTPUBREC      5 << 4  // Publish Received (assured delivery part 1)
#define MQTTPUBREL      6 << 4  // Publish Release (assured delivery part 2)
#define MQTTPUBCOMP     7 << 4  // Publish Complete (assured delivery part 3)
#define MQTTSUBSCRIBE   8 << 4  // Client Subscribe request
#define MQTTSUBACK      9 << 4  // Subscribe Acknowledgment
#define MQTTUNSUBSCRIBE 10 << 4 // Client Unsubscribe request
#define MQTTUNSUBACK    11 << 4 // Unsubscribe Acknowledgment
#define MQTTPINGREQ     12 << 4 // PING Request
#define MQTTPINGRESP    13 << 4 // PING Response
#define MQTTDISCONNECT  14 << 4 // Client is Disconnecting
#define MQTTReserved    15 << 4 // Reserved

#define MQTTQOS0        (0 << 1)
#define MQTTQOS1        (1 << 1)
#define MQTTQOS2        (2 << 1)

class PubSubClient {
private:
   Client* _client;
   uint8_t buffer[MQTT_MAX_PACKET_SIZE];
   uint16_t nextMsgId;
   unsigned long lastOutActivity;
   unsigned long lastInActivity;
   bool pingOutstanding;
   void (*callback)(char*,uint8_t*,unsigned int);
   uint16_t readPacket();
   uint8_t readByte();
   boolean write(uint8_t header, uint8_t* buf, uint16_t length);
   uint16_t writeString(char* string, uint8_t* buf, uint16_t pos);
   uint8_t *ip;
   char* domain;
   uint16_t port;
public:
   PubSubClient(Client& client);
   PubSubClient(uint8_t *, uint16_t, void(*)(char*,uint8_t*,unsigned int),Client& client);
   PubSubClient(char*, uint16_t, void(*)(char*,uint8_t*,unsigned int),Client& client);
   boolean connect(char *);
   boolean connect(char *, char *, char *);
   boolean connect(char *, char *, uint8_t, uint8_t, char *);
   boolean connect(char *, char *, char *, char *, uint8_t, uint8_t, char*);
   void disconnect();
   boolean publish(char *, char *);
   boolean publish(char *, uint8_t *, unsigned int);
   boolean publish(char *, uint8_t *, unsigned int, boolean);
   boolean publish_P(char *, uint8_t *, unsigned int, boolean);
   boolean subscribe(char *);
   boolean loop();
   boolean connected();
};


#endif

答案 12 :(得分:2)

将Unicode Int转换为String

对于想要将Int转换为Unicode字符串的用户,可以执行以下操作:

let myInteger: Int = 97

// convert Int to a valid UnicodeScalar
guard let myUnicodeScalar = UnicodeScalar(myInteger) else {
    return ""
}

// convert UnicodeScalar to String
let myString = String(myUnicodeScalar)

// results
print(myString) // a

或者:

let myInteger: Int = 97
if let myUnicodeScalar = UnicodeScalar(myInteger) {
    let myString = String(myUnicodeScalar)
}

答案 13 :(得分:2)

我使用这种简单的方法

Int to Int:

 var a = Int()
var string1 = String("1")
a = string1.toInt()

从Int到String:

var a = Int()
a = 1
var string1 = String()
 string1= "\(a)"

答案 14 :(得分:1)

let a =123456888
var str = String(a)

OR

var str = a as! String

答案 15 :(得分:0)

let Str = "12"
let num: Int = 0
num = Int (str)

答案 16 :(得分:0)

exampleLabel.text = String(yourInt)

答案 17 :(得分:0)

将String转换为Int

var numberA = Int("10")

Print(numberA) // It will print 10

将Int转换为字符串

var numberA = 10

第一路)

print("numberA is \(numberA)") // It will print 10

第二路)

var strSomeNumber = String(numberA)

var strSomeNumber = "\(numberA)"

答案 18 :(得分:0)

在swift 3.0中,您可以将整数更改为字符串,如下所示

let a:String = String(stringInterpolationSegment: 15)

另一种方式是

let number: Int = 15
let _numberInStringFormate: String = String(number)

//或任何整数代替15

答案 19 :(得分:0)

我更喜欢使用String Interpolation

let x = 45
let string = "\(x)"

每个对象都有一些字符串表示形式。这使事情变得简单。例如,如果您需要创建一些具有多个值的String。您也可以在其中进行任何数学运算或使用某些条件

let text = "\(count) \(count > 1 ? "items" : "item") in the cart. Sum: $\(sum + shippingPrice)"

答案 20 :(得分:0)

如果您想快速扩展,可以添加以下代码

extension Int
{
    var string:String {
        get {
            return String(self)
        }
    }
}

然后,您可以通过刚添加的方法获取字符串

var x = 1234
var s = x.string

答案 21 :(得分:0)

关于性能的一点点 在装有iOS 14的iPhone 7(真实设备)上UI Testing Bundle

let i = 0
lt result1 = String(i) //0.56s 5890kB
lt result2 = "\(i)" //0.624s 5900kB
lt result3 = i.description //0.758s 5890kB
import XCTest

class ConvertIntToStringTests: XCTestCase {

    let count = 1_000_000
    
    func measureFunction(_ block: () -> Void) {
        
        let metrics: [XCTMetric] = [
            XCTClockMetric(),
            XCTMemoryMetric()
        ]
        let measureOptions = XCTMeasureOptions.default
        measureOptions.iterationCount = 5
        
        measure(metrics: metrics, options: measureOptions) {
            block()
        }
    }

    func testIntToStringConstructor() {
        var result = ""
        
        measureFunction {
            
            for i in 0...count {
                result += String(i)
            }
        }

    }
    
    func testIntToStringInterpolation() {
        var result = ""
        
        measureFunction {
            for i in 0...count {
                result += "\(i)"
            }
        }
    }
    
    func testIntToStringDescription() {
        var result = ""
        measureFunction {
            for i in 0...count {
                result += i.description
            }
        }
    }
}

答案 22 :(得分:-1)

从字节中获取字符串:[UInt8] :( swift3及更高版本)

使用以下代码

if let string = String(bytes: bytes, encoding: .utf8) {
    print(string)
} else {
    print("not a valid UTF-8 sequence")
}

答案 23 :(得分:-1)

let intAsString = 45.description     // "45"
let stringAsInt = Int("45")          // 45