What is the difference between "like string" and "stringvalue" in swift?

I have a code:

var i : AnyObject! i = 10 println(i as String) println(i.stringValue) 

it breaks into a string as String , but works in the second i.stringValue .

What is the difference between String and stringValue in the above lines?

+5
source share
3 answers

.stringValue is a way to extract Integer into a string value, but as String will not work for this. And if you use as String , then Xcode will force you to add ! with as , which is not very good and it will never succeed, and this will crash your application. you cannot impose Int on String . He will always fail. That is why when you do as! String as! String , this causes the application to crash.

So casting here is not a good idea.

And here are some more ways to extract Integer into a string value:

 let i : Int = 5 // 5 let firstWay = i.description // "5" let anotherWay = "\(i)" // "5" let thirdWay = String(i) // "5" 

Here you cannot use let forthway = i.stringValue , because Int does not have a member named stringValue

But you can do the same with anyObject , as shown below:

 let i : AnyObject = 5 // 5 let firstWay = i.description // "5" let anotherWay = "\(i)" // "5" let thirdWay = String(i) // "5" let forthway = i.stringValue // "5" // now this will work. 
+7
source

Both pass Int to String, but this will no longer work. In Swift 2, this is not possible to do so.

U should use:

 let i = 5 print(String(format: "%i", i)) 

This will intentionally write the int value as a string

+1
source

with as String , you cannot specify a value, but you determine that the variable contains String , but in your case it is Int .so it will work.

while the other way, i.e. i.stringValue , converts your value to String . Therefore, it does not give you any failure and passes successfully to the String value.

Note. Since you are using AnyObject , the variable has a stringvalue member ... but Int does not ... To display the value of the Int value, execute @Dharmesh Kheni answer

+1
source

Source: https://habr.com/ru/post/1232508/


All Articles