Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions Algorithms/TwoSum.playground/Contents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,36 @@ let integers: [Int] = [2, 5, 4, 12, 7]
Фукция должна возвращать индексы двух чисел из массива array,
сумма которых равна переданному значению target
*/
//func findTarget(_ target: Int, in array: [Int]) -> [Array<Int>.Index] {
// // Ваша реализация
// for i in 0..<array.count {
// for j in i+1..<array.count {
// if array[i] + array[j] == target {
// return [i, j]
// }
// }
// }
//
// return []
//}

func findTarget(_ target: Int, in array: [Int]) -> [Array<Int>.Index] {
// Ваша реализация

return [0, 1]
var dict = [Int: Int]()

for i in 0..<array.count {
dict[array[i]] = i
}

for key in dict.keys {
if let anotherIndex = dict[target - key] {
return [dict[key]!, anotherIndex]
}
}

return []
}

// Ожидаемый ответ [2, 3]
findTarget(16, in: integers)

Binary file not shown.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>Rainy.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
</dict>
</dict>
</dict>
</plist>
Binary file not shown.
35 changes: 1 addition & 34 deletions SwiftStyle/Rainy/Rainy/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,43 +10,10 @@ import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


// MARK: UIApplicationDelegate methods
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}

func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}



func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


}





121 changes: 72 additions & 49 deletions SwiftStyle/Rainy/Rainy/CurrentWeatherViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ import CoreLocation
import Alamofire
import SwiftyJSON



struct coords{
struct coords {
var lat: Double = 0
var lon: Double = 0
}
Expand All @@ -27,9 +25,10 @@ class CurrentWeatherViewController: UIViewController, CLLocationManagerDelegate
@IBOutlet weak var imageWeather: UIImageView!

private var locationManager: CLLocationManager!
// private let constrain: Constants = Constants()

// private let constrain: Constants = Constants()
private var currentForecast: WeatherForecast? {
didSet{
didSet {
reloadUI()
}
}
Expand All @@ -54,115 +53,139 @@ class CurrentWeatherViewController: UIViewController, CLLocationManagerDelegate
"50d":#imageLiteral(resourceName: "fog"),
"50n":#imageLiteral(resourceName: "fog")]


private var myCoords: coords = coords()


// MARK: UIViewController methods
override func viewDidLoad() {
super.viewDidLoad()

locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
if(CLLocationManager.authorizationStatus() == .notDetermined){

if(CLLocationManager.authorizationStatus() == .notDetermined) {
locationManager.requestWhenInUseAuthorization()
}

if CLLocationManager.locationServicesEnabled(){
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
}
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
self.updateCurrentForecast()
})
}
}

// MARK: IBActions
@IBAction func reloadButtonPressed(_ sender: AnyObject) {
if(CLLocationManager.authorizationStatus() == .notDetermined){
if(CLLocationManager.authorizationStatus() == .notDetermined) {
locationManager.requestWhenInUseAuthorization()
}

if CLLocationManager.locationServicesEnabled(){
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
}

updateCurrentForecast()
}


internal func locationManager(_ manager: CLLocationManager,
didFailWithError error: Error) {
print("error: ", error)

// MARK: Internal methods
internal func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("error: \(error)")
}

internal func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.myCoords.lat = locations[0].coordinate.latitude
self.myCoords.lon = locations[0].coordinate.longitude

locationManager.stopUpdatingLocation()
}


private func updateCurrentForecast(){
Alamofire.request("http://api.openweathermap.org/data/2.5/weather",method: .get,parameters: ["lat":myCoords.lat,"lon": myCoords.lon,"APPID": "","units":"metric"],encoding: JSONEncoding.default,headers: nil).responseJSON{response in
guard response.result.isSuccess else{
return
}
let json = JSON(response.result.value!)
self.currentForecast = WeatherForecast(currentWeatherTempurature: round(10 * json["main"]["temp"].doubleValue) / 10,
timeStamp: self.getCurrentTime(),
imageName: json["weather"][0]["icon"].string!,
locationCoordinates: (self.myCoords.lat, self.myCoords.lon),
humidity: json["main"]["humidity"].int,
pressure: json["main"]["pressure"].int,
wind: round(10 * json["wind"]["speed"].doubleValue) / 10, cityName: json["name"].string,
stateWeather: json["weather"][0]["description"].string)
// MARK: Private methods
private func updateCurrentForecast() {
Alamofire.request("http://api.openweathermap.org/data/2.5/weather",
method: .get,
parameters: ["lat":myCoords.lat, "lon": myCoords.lon, "APPID": "", "units":"metric"],
encoding: JSONEncoding.default,
headers: nil).responseJSON { response in
guard response.result.isSuccess else {
return
}

guard let resultValue = response.result.value else {
return
}

let json = JSON(resultValue)

self.currentForecast = WeatherForecast(currentWeatherTempurature: round(10 * json["main"]["temp"].doubleValue) / 10,
timeStamp: self.getCurrentTime(),
imageName: json["weather"][0]["icon"].string!,
locationCoordinates: (self.myCoords.lat, self.myCoords.lon),
humidity: json["main"]["humidity"].int,
pressure: json["main"]["pressure"].int,
wind: round(10 * json["wind"]["speed"].doubleValue) / 10,
cityName: json["name"].string,
stateWeather: json["weather"][0]["description"].string)
}
}

private func getTrafficInformation(){
Alamofire.request("http://www.mapquestapi.com/traffic/v2/incidents",
parameters: ["boundingBox": "\(myCoords.lat),\(myCoords.lon),\(myCoords.lat - 1),\(myCoords.lon - 1)",
"key": ""])
.responseJSON{response in
guard response.result.isSuccess else{
.responseJSON { response in
guard response.result.isSuccess else {
return
}

guard let resultValue = response.result.value else {
return
}
_ = JSON(response.result.value!)
_ = JSON(resultValue)
}
}

private func getCurrentTime() -> String{
private func getCurrentTime() -> String {
let date = NSDate()
let calendar = NSCalendar.current
var currentTime: String
let components = calendar.dateComponents([.hour, .minute], from: date as Date!)
var hour: String = String(describing: components.hour!)
var minute: String = String(describing: components.minute!)
if hour.characters.count == 1{

if hour.characters.count == 1 {
hour = "0" + hour
}
if(minute.characters.count == 1){
if(minute.characters.count == 1) {
minute = "0" + minute
}

currentTime = "\(hour):\(minute)"

return currentTime
}



private func reloadUI(){
timeLabel.text = "Updated: \(currentForecast!.timeStamp)"
if let temp = currentForecast?.currentWeatherTempurature{
guard let currentForecast = currentForecast else {
return
}

timeLabel.text = "Updated: \(currentForecast.timeStamp)"

if let temp = currentForecast.currentWeatherTempurature {
temperatureLabel.text = "\(temp)℃"
}
if let city = currentForecast?.cityName{
if let city = currentForecast.cityName {
cityNameLabel.text = city
}
if let wi = currentForecast?.wind{
if let wi = currentForecast.wind {
windLabel.text = "\(wi)"
}
if let st = currentForecast?.stateWeather{
if let st = currentForecast.stateWeather {
stateLabel.text = st
}
imageWeather.image = photoResources[(currentForecast?.imageName)!]

imageWeather.image = photoResources[currentForecast.imageName]
}
}


Loading