Copy string value to another string? - ios

var phoneUDID: String?
var temporaryUDID: String?
var customUDID: String?
let md5Data = MD5(string: UIDevice.current.identifierForVendor!.uuidString)
let md5Hex = md5Data.map { String(format: "%02hhx", $0) }.joined()
self.phoneUDID = md5Hex
self.temporaryUDID = (md5Hex + "#gmail.com")
self.customUDID = self.temporaryUDID
Information: I am using Swift 3 by the way!
Question: Is the self.customUDID = self.temporaryUDID line correct to use? Since they are both strings, is this a safe way of copying a string's value to another string? I submitted my app to the app store and saw this booboo and thought that errors could arise. Please convince me i'm safe. Thanks

String is a value type in Swift. So no, if you change one, the other won't change.
When you do
self.customUDID = self.temporaryUDID
A new string is created and stored in customUDID.
Example:
var s1 = "Foo"
var s2 = s1
s1 = "Bar"
print(s1,s2) //Prints "Bar Foo"

Related

How to remove 1 component in a string? Swift

I have this string "01:07:30" and I would like to remove the zero in "01" and keep everything else the same. My final string should look like this
"1:07:30"
Is there a way to do so in Swift? Thank you so much!
Try the following. This will create a string, check to see if the first character is 0 if it is remove it. Otherwise do nothing.
var myString = "01:07:30"
if myString.first == "0" {
myString.remove(at: myString.startIndex)
}
print(myString) // 1:07:30
The final result is the string will now be 1:07:30 instead of 01:07:30.
If I'm best understanding your question, you want to replace the occurrences of "01" with "1" in your string, so you can use regex or the string functionality it self
simply:
let searchText = "01"
let replaceWithValue = "1"
let string = "01:07:08:00:01:01"
let newString = string.replacingOccurrences(of: searchText, with: replaceWithValue) // "1:07:08:00:1:1"
If you want to replace the fist occurrence only, simply follow this answer:
https://stackoverflow.com/a/33822186/3911553
If you just want to deal with string here is one of many solution:
var myString = "01:07:30"
let list = myString.components(separatedBy: ":")
var finalString = ""
for var obj in list{
if obj.first == "0" {
obj.removeFirst()
}
finalString += finalString.count == 0 ? "\(obj)" : ":\(obj)"
}
print(finalString)

Swift String operation not working

I am trying to read the string from a Label and remove the last character form it.
This is how I am trying:
#IBAction func del(sender: UIButton) {
let str = telephone.text!;
let newstr = str.remove(at: str.index(before: str.endIndex))
telephone.text = newstr;
}
When I run, I get an error:
"String" does not have a member named "remove"
Can someone help me figure out the problem?
Just started learning swift :(
remove(at:) mutates the receiver which must therefore be a variable
string:
var str = telephone.text!
str.remove(at: str.index(before: str.endIndex))
telephone.text = str
Alternatively use substring(to:), which returns the new string
instead of modifying the receiver:
let str = telephone.text!
let newstr = str.substring(to: str.index(before: str.endIndex))
telephone.text = newstr
remove is defined as follows:
public mutating func remove(at i: String.Index) -> Character
See the mutating modifier? That means it mutates the instance on which the method is called. In your case, the instance is str, a constant. Since constants cannot be mutated, the code does not compile.
And since remove returns the removed character,
let newstr = str.remove(at: str.index(before: str.endIndex))
here newstr will not be storing the string with the last character removed.
You should rewrite the method like this:
telephone.text!.remove(at: telephone.text!.index(before: telephone.text!.endIndex))
You can use:
let idx = str.index(before: str.endIndex) // compute the index
let s = str.substring(to: idx) // get the substring

Short Random Unique alphanumeric keys similar to Youtube IDs, in Swift

Is there a way to create random unique IDs similar to the YouTube IDs in Swift?
I know there are similar answers on this link, but they are for Php. But I want something in Swift.
I have tried using timestamp and UUIDs, but I want an alphanumeric short keys which would be around 4-10 characters so users can easily share with others verbally.
Thanks.
Looking for just a unique string
You can use UUIDs they're pretty cool:
let uuid = NSUUID().UUIDString
print(uuid)
From the  docs
UUIDs (Universally Unique Identifiers), also known as GUIDs (Globally
Unique Identifiers) or IIDs (Interface Identifiers), are 128-bit
values. UUIDs created by NSUUID conform to RFC 4122 version 4 and are
created with random bytes.
Some info about uuid: https://en.wikipedia.org/wiki/Universally_unique_identifier
Looking for a more specific length
Try something like this:
func randomStringWithLength(len: Int) -> NSString {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let randomString : NSMutableString = NSMutableString(capacity: len)
for _ in 1...len{
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.character(at: Int(rand)))
}
return randomString
}
But i'll keep my answer incase someone else stumbles upon this looking for a UUID
This will allow you to create a random short code. It can create codes from Hexadecimal all the way to base 62 codes and of varying lengths.
aka.
let myCode = ShortCodeGenerator.getCode(length: 6)
3dH7t8,
fdE7j1,
Gl6jKd,
Hv8gU3,
let myBase32Code = ShortCodeGenerator.getCode(withBase: UInt32(32), length: 6)
3HF75J,
J67N9D,
B47SO3,
L9SD2N
You would have to check for redundancy and then create a new one if it has already been used.
struct ShortCodeGenerator {
private static let base62chars = [Character]("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".characters)
private static let maxBase : UInt32 = 62
static func getCode(withBase base: UInt32 = maxBase, length: Int) -> String {
var code = ""
for _ in 0..<length {
let random = Int(arc4random_uniform(min(base, maxBase)))
code.append(base62chars[random])
}
return code
}
}
This answer was useful in creating the above code and also has good
information on the number of unique identifiers you can have with each base number and length.
The total number of unique identifiers you need can be calculated by the equation:
BaseNumber^length = # of unique IDs
EDIT:
I have added even more functionality for converting Int's and NSDate's to shortcodes for my own project as well and put those into a project on GitHub.
Updated for swift 3:
If you want to generate Short Random Unique alphanumeric keys, used below lines of codes;
//function defination:
func generateTransactionId(length: Int) -> String {
var result = ""
let base62chars = [Character]("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".characters)
let maxBase : UInt32 = 62
let minBase : UInt16 = 32
for _ in 0..<length {
let random = Int(arc4random_uniform(UInt32(min(minBase, UInt16(maxBase)))))
result.append(base62chars[random])
}
return result
}
//function call:
let mTranactionId = self.generateTransactionId(length: 5) // you can change the value of length as you want
print("mTranactionId: \(mTranactionId)")
Ex: Result looks like: XHA7K, QTC92, MS1PT, YE2PV
//Enjoy coding...!
Does NSUUID().UUIDString do what you need?
I'm very pleased with NanoID.
https://github.com/ai/nanoid
...and here's the SWIFT version:
https://github.com/antiflasher/NanoID
You just need to drag 1 file (NanoID.swift) into your project, and you are good to go!
TAGS: Short GUID, Short UUID, Short Unique ID, Swift, iOS
Swift custom alternative(these version doesn't check for duplicate char):
func randomString(length: Int) -> String {
let letters = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
var randomString: String = ""
for _ in 0..<length {
let randomNumber = Int.random(in: 0..<letters.count)
randomString.append(letters[randomNumber])
}
return randomString
}
You can archive this just using UUID.
If you don't want the whole string, as any String in Swift, you select a small portion of the string by using range, like this:
let text = UUID().uuidString
let index = text.index(text.startIndex, offsetBy: 8)
let small = text[text.startIndex..<index]
Notice 8 is the length of string I suggested, you can improve this by clamping this value using min(size, text.count) for example.
And finally, small is a Substring, to cast it to String just cast as usual - String(small)
Swift 5 version using a String extension
extension String {
static func random(length: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<length).compactMap { _ in
letters.randomElement()
})
}
}

If let var - Unwrapping optional value

There is some ways to unwrap an optional value:
// 1st way
var str: String? = "Hello, playground"
if let strUnwrapped = str {
// strUnwrapped is immutable
println(strUnwrapped)
}
// 2nd way
var str: String? = "Hello, playground"
if var strUnwrapped = str {
// strUnwrapped is mutable
strUnwrapped = "Toldino"
println(strUnwrapped)
}
But I recently test this following one...
// The strangest one
var str: String? = "Hello, playground"
if let var strUnwrapped = str {
// strUnwrapped is mutabe
strUnwrapped = "yolo"
println(strUnwrapped)
}
Can you explain me why does it work ?
It is a bug or a functionality ?
EDIT
As niñoscript said, it was a bug.
It is resolved in Swift 2.0, I tried it with the new version and it doesn't compile anymore.
Now Xcode throw this following error for "if let var"
This answer is only valid for Xcode 6, the bug was fixed in Xcode 7 as noted by the OP's edit and Paul Jarysta's answer
In this case:
if let var strUnwrapped = str {}
let var works the same way as just var, so either it is a bug or it's just the same thing. But if you try the following simple code:
let var n = 3
It throws this error:
'var' cannot appear nested inside another 'var' or 'let' pattern
So we can safely assume that it is a bug. We should be good developers and report it!
This problem was solved in xcode 7 ;-)

Swift, get variable name from a string

I have a question. I know that this can be done in Ruby, not sure about Swift, but never did anything similar.
What I'm working on is a program that works similar to this: if the user writes in a TextView "a + b", my code should elaborate the value of the sum between the variable "a" and "b".
What I mean is, how can I get variable names from a string? Is it possible at all?
If it's not, I'd use a switch (variable names are limited), but I'd need to "connect" a variable to the one written by the user. In the example, if the user writes "a + b", my sum function is something like "sum(par1,par2)", so, how can I make variable "par1" point to "a" and "par2" point to "b"? I can do that with pointers right? Is there any other way?
I'm not sure I've been clear, but it's quite hard to explain
Check this out. You can do with NSExpression and KVC.
class myclass:NSObject {
var a = 10;
var b = 20;
override init() {
super.init();
}
}
var obj = myclass();
// Expression from user
var expr:NSString = "a+b" ;
//Operators..
let opSet = NSMutableCharacterSet()
opSet.addCharactersInString("+-*/");
let components:NSArray = expr.componentsSeparatedByCharactersInSet(opSet)
let uniqueChars:NSSet = NSSet(array: components)
for variable in uniqueChars
{
expr = expr.stringByReplacingOccurrencesOfString ( variable as String,
withString : NSString(format: "%d", obj.valueForKey(variable as String) as Int),
options : NSStringCompareOptions.LiteralSearch,
range : NSMakeRange(0,expr.length) );
}
var result: AnyObject = NSExpression(format: expr).expressionValueWithObject(nil, context: nil)
print (result);

Resources