I'm afraid this question does not match what this site is about. Code Review is about improving the cleanliness of existing, working code. Code Review is not the site to ask for help in fixing or changing what your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! — Simon André Forsberg56 secs ago
Welcome to Code Review! This is a nice first answer! Excellent point that the reversing-twice approach can be used to minimize storage. — Simon André Forsberg1 min ago
enum ServerResponse {
case Result(String, String)
case Error(String)
}
let success = ServerResponse.Result("6:00 am", "8:09 pm")
let failure = ServerResponse.Error("Out of cheese.")
switch success {
case let .Result(sunrise, sunset):
let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
case let .Error(error):
let serverResponse = "Failure... \(error)"
}
> From Apple news books, "Using Swift with Cocoa and Objective-C". Runtime exceptions not occur using swift languages, so that's why you don't have try-catch.
I haven't read too much into Swift but one thing that i noticed is there are no exceptions.
So how do they do error handling in swift? Has anyone found anything to error-handling?
Here's my attempt at a Caesar Cipher encoder/decoder.
If given a key, it will encrypt the given string.
However, if you do not specify a key, it checks each of the 26 possible keys and returns the one with the highest percentage of words that appear in this file of English words (with a couple a...
public static int getMenuOption()
public static double getOperand(String prompt)
public static double add(double operand1, double operand2)
public static double subtract(double operand1, double operand2)
public static double multiply(double operand1, double operand2)
public static double divide(d...
It's just odd that their driving motivation was to get rid of the C in Objective C, but they're still apparently sticking with C style error checking (though with slightly prettier syntax).
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
What I've so far learned about Swift is that while the Playground is very cool ...
So try-catches are shunned because you shouldn't be writing code that throws exceptions.
But consider this block of Swift code:
extension Int {
func reversed() -> Int {
var original: Int = self
var reversed: Int = 0
while original > 0 {
reversed *= 10
reversed += original % 10
original /= 10
}
return reversed
}
}
let bigInt: Int = Int.max - 8
let overflow = bigInt.reversed()
Makes sense (if you're into C error handling), but it's still strange to not have exceptions at all. There's still asserts and return codes, of course, but... meh.
I don't know. I think it's just as an ObjC/swift outsider, it's a little weird.
Though I did ObjC for 6 months, and the error handling never quite felt pleasant.
But then again, exceptions can be just as unpleasant
If you reverse that, it's > Int.max, so it overflows
I think in Objective-C, it'd just be undefined behavior (integer overflow)
Guess what happens in Swift?
Playground execution failed: error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
* thread #1: tid = 0x13299, 0x000000010f61d82c, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
* frame #0: 0x000000010f61d82c
Every error doesn't necessarily need to be an exception, but they're a very nice facility to have. I think it just comes down to Apple clearly has a different philosophy than I do.
I just never feel quite safe with C style error handling. what if i forgot to check an error code? suddenly I have a program with some rather odd, sporadic behavior, and I'm going to have a hell of a time tracking that down. Uncaught exceptions leave a much better debugging trail, and they give me a peace of mind that my code is reasonably robust.
Then again, I guess typical code really doesn't have that much error handling. It's just low level or library type things.
I do, for sure, but the average user is a raly dum moran.
And when you're Apple, both the device AND the OS are your product.
There are millions of apps on the app store, and Apple gets a piece of all of their profits. But what's ultimately most important to them is that the user not be led to believe that the operating system or the device are bad.
Anyway, Corbin, unless your app is in one of a very few specific categories, to do stuff in the background, you register with the OS as an app that wants to do background stuff.
As well, you set a minimum time between updates. You can't set a maximum, but you can set a minimum (so you only do a background task once per hour at most, for example)
Whenever the OS deems it convenient, it wakes your app up with a method to the app delegate. It passes in a function pointer.
You have 30 seconds to execute code, and then call the function that was passed in with one of three arguments, which indicates "No new data," "new data," or "error".
Using your apps returns from this function, as well as a ton of other metrics such as current device battery life, how busy the processor currently is, how frequently the user uses your app, etc., the device decides when you get to do background updates.
Are you teaching yourself Swift via reviewing my Project Eulers? ;) — nhgrif16 secs ago
@rolfl "The print in the function is.... ugly." For the record... it originally wasn't, but I wanted to move it into the printTimeElapsedWhenRunningCode
But for the future Project Euler solutions, I'm going to take this approach:
func solution() {
let firstTwentyInts: [Int] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
let answer: Int = leastCommonMultiple(firstTwentyInts)
println(String(answer))
}
printTimeElapsedWhenRunningCode("Least Common Multiple", solution)
@nhgrif - I believe a novice reviewing an expert's code is often a good thing.... it makes the expert stop and think about how people see them think, and how they express things.
I know nothing about swift, but I can see algorithm and other issues in your code.
I'm focusing on other things and forgetting about some of the things you point out, which would be obvious to me if I were writing Objective-C actually
Put it together, I will get enough of an ability to read swift to know when people are doing the right thng, and when people are trying to BS me ;-)
Youa re doing the right thing, but I can see those 'lazy' decisions too. I use the word lazy like a true programmer would. Normally lazy is good. but on code review, we strive for better uses of lazy
Also, about your questions, Apart from the two swift ones I did (one last night, and one today), I have not answered any main-site questions for almost a week.
Meta has taken up most of my allotment of CR time.
@nhgrif eh that's just basic resource sharing though. All OS's do that, just not to such a great extent, since windowing gives you a more visible control over background processes typically. It is interesting though that there's no guaranteed minimal period to be called again. It makes sense though.
Thought I would apply what I learned to make something fun. Its purpose is to type check pokemon for anyone familiar with the series. It mostly works but I have two concerns.
First, Sometimes you write code and you get the pervading feeling you're not using some method, some API or the best appr...
If you only use my app once a day and you always use it around 7am, then no matter what I set my background stuff up for, it's very likely that the OS will eventually optimize it so that my app only gets opportunity to check for updates once between 6am and 6:59am and then at no other part of the day.
I've only just started using this stuff though, so I'm not certain exactly how good it is, but supposedly it's extraordinarily good at doing no more than absolutely necessary.
Android, of course is less limiting, which has its advantages. And if the user knows what they're doing, they can potentially get more out of their Android device than they can their iOS device.
But if the user doesn't really know what they're doing, and they download some nefarious app that's doing stuff in the background, well now their app is massively draining the device's battery, or using up RAM, or competing for processor time.
And to you or I or anyone who knows what they're doing, we start looking at what's going on with the device, and try to find out why we're getting poor performance.
But to the average, less tech-savvy user, there's a huge optics problem.
Because the actual problem is in the background... where a less tech savvy user won't notice it.
They are more likely to associate the poor performance with the active app or the poor battery life with the device.
It isn't clear if this question has already been answered, so apologies in advance if this is a duplicate :
I am implementing a game and trying to design around a clean MVC pattern - so my Control plane will implement the rules of the game (but not how the game is displayed), and the View plane...
can somebody give me a java program which will find the index of the element whose value is the sum of the remaining elements.
I have to tried to write the code but I couldnt write a simplified code. Iam myself writing a cumbersome logic but couldnt simplify it. can anybody help me in resolving...
**[skiwi2/GithubHookSEChatService]** **skiwi2** pushed commit **5331db63** to **master** > The chat throttle amount can now be set via the properties file.
I know it works if I use single lines, but then I need to fix my chat throttling
There are \$0\$ cells on day \$0\$. Each day, cells multiply by \$x\$ times and \$y\$ humans die. Find number of humans on day \$n\$(after they multiply and die).
Closed form of cells on day \$n=x^n-y^n\frac{x^n-1}{x-1}\$
\$−1<x<101\$
\$−1<y<x−1\$
\$0<n<10^6+1\$
As answer can be very large, ...
The code review section of stack exchange was recommended to me in my original thread, so I'm going to copy my original post. Basically I could use some tips on adding every step (as explained below) into its own methods. Thanks again.
I'm new to c# so be ready for some dumb questions.
My cu...
We'll be traveling to China,what are the best places to see IN Beijing ?China is a vast and interesting country.The language barrier should be the number one hurdle to overcome for a foreigner when traveling to beijing. Beijing: China’s capital city of Beijing has numerous world-class sites. Ther...
What is correct way to handle connections for QSqlDatabase?
In my program I am doing it this way:
DatabaseConnector *databaseConnector = 0;
try
{
databaseConnector = new DatabaseConnector();
//Do stuff...
delete databaseConnector;
}
catch(QString e)
{
delete databaseConnector;
...
Given an array of ints, is it possible to divide the ints into two groups, so that the sum of one group is a multiple of 10, and the sum of the other group is odd. Every int must be in one group or the other. Write a recursive helper method that takes whatever arguments you like, and make the ini...
i am new to iOS/swift,
i have create a UISegmentedControl and a view under it ,
the view under contains all a view for each segment
i am doing animation when the segment is changing.
a couple of questions :
1) dose a center view that contain all subview is the right approch ?
2) is the animati...
again! Here is my program that turns numbers into text, it can be extended to Millions, Billions, Trillions and so on. Please review my code and here is what I expect from the users:
Is there any better variable names, function names, you can give me? Or my given names are okay? If you've bette...
I have a navigation bar without a tags, here's my code:
$('div.nav ul li').on('click', function() {
if($(this).is(':first-child')) {
$("html, body").animate({
scrollTop: "0"
}, 'slow');
} else if($(this).is(':nth-child(2)')) {
...
How should it be handled if a User asks a question where the original problem is from some website and under copyright?
For example this question quotes a problem from a website which says at the bottom Copyright [person] 2006-11.
I basically have three question:
is this a legal problem or i...
> As a systems hacker, you must be prepared to do savage things, unspeakable things, to kill runaway threads with your bare hands, to write directly to network ports using telnet and an old copy of an RFC that you found in the Vatican.
and then:
> HCI people discover bugs by receiving a concerned email from their therapist. Systems people discover bugs by waking up and discovering that their first-born children are missing and “ETIMEDOUT ” has been written in blood on the wall.
> This is not the world of the systems hacker. When you debug a distributed system or an OS kernel, you do it Texas-style. You gather some mean, stoic people, people who have seen things die, and you get some primitive tools, like a compass and a rucksack and a stick that’s pointed on one end, and you walk into the wilderness and you look for trouble,
> Why not use a modern language with garbage collection and functional programming and free massages after lunch?” Here’s the answer: Pointers are real. They’re what the hardware understands. Somebody has to deal with them. You can’t just place a LISP book on top of an x86 chip and hope that the hardware learns about lambda calculus by osmosis.
Python 3 - 74
Although it's not the shortest, it does do something useful: calculates Pi to unprecedented accuracy.
Just in case you were wondering, this program loops 1E2000 times. That should outlive the universe by far.
p=0
for i in range(1000**1000):
if i%2==0:p+=4/(i*2+1)
else:p-=4/(i*2...
I've implemented a simple C++ STL like deque. It's pretty simple, all the constructors and methods haven't been implemented here, but majors are.
#ifndef DEQUE_H
#define DEQUE_H
#include <iostream>
#include <stdexcept>
template <typename T>
class deque {
public:
deque <T> & operator = (c...
one of my better answers and only 2 upvotes? @Mat'sMug @BenVlodgi and all you other C# experts programmers check it out, make sure I am not a rambling idiot.
This switch should be an if statement instead.
if (input == null) // we didn't get an input from GetCustomEditorInput
{
switch (property.PropertyType.Name)
{
case "Boolean":
input = new ExpressFormsCheckBox()
...
right now I need to install some vbscript to the 3rd party app
Guice doesn't seem to play ball with decorators and wants you to use aspects.
simply put, I need to defer X methods of a class onto a thread. They need to go through this thread. I can either use aspects to do this or I can use a decorator for the entire class
@BenVlodgi I live in South Dakota, it's cold here in the winter, I want to move south to somewhere like Tennessee or somewhere close to there, in the smoky mountains...
@BenVlodgi they would be some complex ternaries. I was trying to wrap my head around what I did there.... :) but I see what you are saying, can you put a block of code inside of a ternary statement?
> You've earned the "Necromancer" badge (Answered a question more than 60 days later with score of 5 or more) for "Logging into WebAPI 2 site from c# desktop application".