how to convert characterIsMember objective c to swift [closed] - objective-c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have one part code objective c code and I want to convert to swift :
NSString *rawStr = [[tokenField textField] text];
for (int i = 0; i < [rawStr length]; i++)
{
if (![charSet characterIsMember:[rawStr characterAtIndex:i]])
{
[recipient appendFormat:#"%#",[NSString stringWithFormat:#"%c", [rawStr characterAtIndex:i]]];
}
}
if ([rawStr length])
{
[tokenField addTokenWithTitle:rawStr representedObject:recipient];
}
please guide me about that.

If you don't mind using NSString the port is straight forward:
let rawStr:NSString = tokenField.textField.text
for i in 0..<rawStr.length {
let currentChar = rawStr.characterAtIndex(i)
if !charSet.characterIsMember(currentChar) {
recipient.appendFormat("%#", NSString(format:"%c", currentChar))
}
}
if rawStr.length > 0 {
tokenField.addTokenWithTitle(rawStr, representedObject:recipient)
}
Else the String class does not have a length method. You'll have to use s.startIndex.advancedBy syntax.

Looks like you are trying to keep characters that are not in your character set.
func strRemoveCharsNotInSet(str: String) -> String {
let charSet = NSCharacterSet(charactersInString: ".#")
let temp = str.componentsSeparatedByCharactersInSet(charSet)
let backToString = temp.joinWithSeparator("")
return backToString
}
print(strRemoveChars("Hello#There.Friend"))
outputs:
HelloThereFriend

Related

Objective-C to Swift conversion for C function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am facing difficulties in Objective-C to Swift conversion. How to write below code in Swift?
int mib[2];
size_t length;
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
length = sizeof(int64_t);
sysctl(mib, 2, &physicalMemorySize, &length, NULL, 0);
mib[1] = HW_USERMEM;
length = sizeof(int64_t);
sysctl(mib, 2, &userMemorySize, &length, NULL, 0);
It is not too difficult if one knows two things:
The C int type is a 32-bit integer, this is Int32 in Swift,
not Int.
sizeof() from C is MemoryLayout<T>.stride in Swift.
Then we get:
var mib : [Int32] = [ CTL_HW, HW_MEMSIZE ]
var physicalMemorySize: Int64 = 0
var size = MemoryLayout<Int64>.stride
if sysctl(&mib, UInt32(mib.count), &physicalMemorySize, &size, nil, 0) == 0 {
print(physicalMemorySize)
} else {
print("sysctl failed")
}

Differences in for-loops. Swift v.s. Objective-C [duplicate]

This question already has answers here:
Removing from array during enumeration in Swift?
(9 answers)
Closed 6 years ago.
In this loop we have the potential to reduce the number of items in the loop while processing it. This code works fine in Obj-C, but the Swift loops don't get the message that an item has been removed and end up overflowing the array.
In Objective-C, we had:
for(int i = 4; i < staticBlocks.count; i++)
{
PlayerSprite* spr = [staticBlocks objectAtIndex:i];
[spr setPosition:CGPointMake(spr.position.x, spr.position.y-1)];
if(spr.position.y < -1000)
{
[staticBlocks removeObject:spr];
[spr removeFromParent];
}
if(spr.blockTypeIndex == Block_Type_Power_Up)
{
[spr update];
}
}
In Swift I know of these options:
//for i in 4.stride(to: staticBlocks.count, by: 1){ //crashes
//for i in 4..<staticBlocks.count{ //crashes
for var i = 4; i < staticBlocks.count; i += 1 { //works, but is deprecated
let spr = staticBlocks.objectAtIndex(i) as! PlayerSprite
spr.position = CGPointMake(spr.position.x, spr.position.y-1)
if(spr.position.y < -1000)
{
staticBlocks.removeObject(spr)
spr.removeFromParent()
//break
}
if(spr.blockTypeIndex == k.BlockType.PowerUp)
{
spr.update()
}
}
In this specific case, it really isn't a problem for me to use a break statement (which is currently commented out) to kill the loop and prevent the crash, but it doesn't seem like the proper fix. I assume there will come a time when I need to know how do do this correctly. Is there a non deprecated way to do a for loop, one which processes the count each pass?
A related, unanswered question.
Is the for loop condition evalutaed each loop in swift?
I don't know how to link to a specific answer, but this code did what I needed. Marking as duplicate now.
Removing from array during enumeration in Swift?
var a = [1,2,3,4,5,6]
for (i,num) in a.enumerate().reverse() {
a.removeAtIndex(i)
}
This is because in Swift you cannot remove items from an array while you are iterating over it.
From this question Removing from array during enumeration in Swift?
you can see that you should be using the filter function instead of using a for loop.
For example, don't do this:
for (index, aString: String) in enumerate(array) {
//Some of the strings...
array.removeAtIndex(index)
}
Do something like this:
var theStrings = ["foo", "bar", "zxy"]
// Filter only strings that begins with "b"
theStrings = theStrings.filter { $0.hasPrefix("b") }
(Code example from this answer)
Additionally, it should be noted that filter won't update the array, it will return a new one. You can set your array to be equal to that array afterwards.
An additional way to solve the issue, from the same question is to do this:
var a = [1,2,3,4,5,6]
for (i,num) in a.enumerate().reverse() {
a.removeAtIndex(i)
}
print(a)

Command Line Calculator in Objective C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to implement a command line application in C/Objective C which will act as a calculator of more than two numbers.
E.g ./calc 5 + 4 * 6
= 29
I just need an idea or simple algorithm to start. I will appreciate any help on this.
The algorithm you want is the infix notation to postfix notation converter.
You can find some more info on it over here.
http://scriptasylum.com/tutorials/infix_postfix/algorithms/infix-postfix/index.htm.
EDIT: I am not sure if this will help, but here is an implementation in Java. I'm not familiar with Objective-C
// converts a infix string to postfix string
private void convertInfixToPostfix(){
// create an empty operand stack
operatorStack = new Stack<>();
Operator operator = null;
Operand operand = null;
for(int i = 0; i < expressionTokens.size(); i++){
String token = expressionTokens.get(i);
Element element = new Element(token);
if(element.isOperand(token)){ // check if element is operand
// add the element to the postfix string
operand = new Operand(element.getStringValue());
postFixString.add(operand);
}
else if(operatorStack.isEmpty()){
// push the token to the operator stack, its an operator
operator = new Operator(element.getStringValue());
operatorStack.push(operator);
}
else {
operator = new Operator(element.getStringValue());
while(!operatorStack.isEmpty() &&
(operatorStack.peek().getPrecedence()
<= operator.getPrecedence()))
postFixString.add(operatorStack.pop());
operatorStack.push(operator);
}
}
// add the rest of the operator stack to the postfix string
while(!operatorStack.isEmpty()){
Operator remainingOperator = operatorStack.pop();
postFixString.add(remainingOperator);
}
}

Convert kilobytes in degrees [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I am trying to program a speedometer! I have a needle image, and I want the needle to rotate according to the current download speed.
I have the following method, but it is not working. When i update my needle with CurrentDegress, it never goes down, only higher and higher; the needle rotates around the circle...Anyone?!
- (void) recalculateDegrees:(CGFloat) currentlyLoadedBytes
{
if(bytes <= 0){
currentDegrees = 0;
}
else if (bytes > completeFileSize){
currentDegrees = MAX_DEGREES;
}
else {
CGFloat log_tmp =(CGFloat) log10f(currentlyLoadedBytes / 1000);
currentDegrees = (log_tmp/5.0f)*290.0f;
}
//code to rotate image to currentDegrees
}
You can use the following method to get the angle from the speed value (and not from currentlyLoadedBytes):
- (CGFloat)angleFromSpeed:(CGFloat)speed
{
if (speed <= 0) {
return MIN_ANGLE;
} else if (speed >= MAX_SPEED) {
return MAX_ANGLE;
} else {
return speed / MAX_SPEED * (MAX_ANGLE - MIN_ANGLE) + MIN_ANGLE;
}
}
I don't follow 100% of what you are doing, but somewhere in your else block you should be dividing currentlyLoadedBytes / completeFileSize. Also, is bytes supposed to be cuurentlyLoadedBytes?

How get a process by know process name on mac os? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
How can i get a process by know process name on mac os?
Just reformatted Haley's answer:
// Return YES if given name process in process list . Otherwise return NO
bool IsInBSDProcessList(char *name) {
assert( name != NULL);
kinfo_proc *result;
size_t count = 0;
result = (kinfo_proc *)malloc(sizeof(kinfo_proc));
if(GetBSDProcessList(&result,&count) == 0) {
for (int i = 0; i < count; i++) {
kinfo_proc *proc = NULL;
proc = &result[i];
if (strcmp(name, proc->kp_proc.p_comm) == 0) {
free(result);
return true;
}
}
}
free(result);
return false;
}
Your question is rather vague. Can you define what you mean by "get a process"?
One method (depending on your definition): launch the Activity Monitor app in Applications/Utilities, and look up the process name in the list.
Perhaps
ps -eaf
from a console