blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
6
116
path
stringlengths
5
872
src_encoding
stringclasses
7 values
length_bytes
int64
10
4.68M
score
float64
2.52
5.63
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
7
4.81M
download_success
bool
1 class
a329aceb8b6cce6914f60ba1ab521658bae997b0
Swift
DenisDorokhov/pony-ios
/Pony/Sources/Models/Realm/ArtistRealm.swift
UTF-8
825
2.84375
3
[]
no_license
// // Created by Denis Dorokhov on 02/05/16. // Copyright (c) 2016 Denis Dorokhov. All rights reserved. // import Foundation import RealmSwift class ArtistRealm: AbstractRealm { dynamic var name: String? let artwork = RealmOptional<Int64>() let albums = LinkingObjects(fromType: AlbumRealm.self, property: "artist") convenience init(artist: Artist) { self.init() id = artist.id name = artist.name artwork.value = artist.artwork } func toArtist(artworkUrl: (Int64?) -> String?) -> Artist { let artist = Artist(id: id) artist.name = name artist.artwork = artwork.value artist.artworkUrl = artworkUrl(artist.artwork) return artist } override static func indexedProperties() -> [String] { return ["name", "artwork"] } }
true
605887482905c374db53d65e412fdd59dbb5a5ad
Swift
NomahCoffee/NCUtils
/NCUtilsExample/ViewController.swift
UTF-8
2,680
2.8125
3
[ "MIT" ]
permissive
// // ViewController.swift // NCUtilsExample // // Created by Caleb Rudnicki on 6/25/21. // import UIKit import NCUtils class ViewController: UIViewController { // MARK: Properties let textField1: NCTextField = { let textField = NCTextField() textField.placeholder = "Standard" textField.activeBorderColor = UIColor.white.cgColor textField.backgroundColor = .systemGray2 return textField }() let textField2: NCEmailTextField = { let textField = NCEmailTextField() textField.placeholder = "Email" textField.backgroundColor = .systemGray2 return textField }() let textField3: NCPasswordTextField = { let textField = NCPasswordTextField() textField.placeholder = "Password" textField.backgroundColor = .systemGray2 return textField }() let textField4: NCPriceTextField = { let textField = NCPriceTextField() textField.placeholder = "Price" textField.setText(with: 3.0) textField.backgroundColor = .systemGray2 return textField }() let textView1: NCTextView = { let textView = NCTextView() textView.placeholder = "Description" textView.text = "This is my description" textView.backgroundColor = .systemGray2 textView.translatesAutoresizingMaskIntoConstraints = false return textView }() let stack: UIStackView = { let stack = UIStackView() stack.axis = .vertical stack.spacing = 8 stack.translatesAutoresizingMaskIntoConstraints = false return stack }() // MARK: Init override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemGray stack.addArrangedSubviews([textField1, textField2, textField3, textField4]) view.addSubviews([stack, textView1]) NSLayoutConstraint.activate([ stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 8), stack.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8), stack.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8) ]) NSLayoutConstraint.activate([ textView1.topAnchor.constraint(equalTo: stack.bottomAnchor, constant: 8), textView1.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8), textView1.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8), textView1.heightAnchor.constraint(equalToConstant: 200) ]) } }
true
96e9b54d0e9e4cba520274caa328a31517ac76aa
Swift
macacajs/XCTestWD
/XCTestWD/XCTestWD/Server/Modules/XCTestWDReponse.swift
UTF-8
2,780
2.75
3
[ "MIT" ]
permissive
// // XCTestWDReponse.swift // XCTestWD // // Created by zhaoy on 24/4/17. // Copyright © 2017 XCTestWD. All rights reserved. // import Foundation import SwiftyJSON import Swifter internal class XCTestWDResponse { //MARK: Model & Constructor private var sessionId:String! private var status:WDStatus! private var value:JSON? private init(_ sessionId:String, _ status:WDStatus, _ value:JSON?) { self.sessionId = sessionId self.status = status self.value = value ?? JSON("") } private func response() -> HttpResponse { let response : JSON = ["sessionId":self.sessionId, "status":self.status.rawValue, "value":self.value as Any] let rawString = response.rawString(options:[])?.replacingOccurrences(of: "\n", with: "") return rawString != nil ? HttpResponse.ok(.text(rawString!)) : HttpResponse.ok(.text("{}")) } //MARK: Utils static func response(session:XCTestWDSession?, value:JSON?) -> HttpResponse { return XCTestWDResponse(session?.identifier ?? "", WDStatus.Success, value ?? JSON("{}")).response() } static func response(session:XCTestWDSession? ,error:WDStatus) -> HttpResponse { return XCTestWDResponse(session?.identifier ?? "", error, nil).response() } //MARK: Element Response static func responseWithCacheElement(_ element:XCUIElement, _ elementCache:XCTestWDElementCache) -> HttpResponse { let elementUUID = elementCache.storeElement(element) return getResponseFromDictionary(dictionaryWithElement(element, elementUUID, false)) } static func responsWithCacheElements(_ elements:[XCUIElement], _ elementCache:XCTestWDElementCache) -> HttpResponse { var response = [[String:String]]() for element in elements { let elementUUID = elementCache.storeElement(element) response.append(dictionaryWithElement(element, elementUUID, false)) } return XCTestWDResponse.response(session: nil, value: JSON(response)) } // ------------ Internal Method --------- private static func dictionaryWithElement(_ element:XCUIElement, _ elementUUID:String, _ compact:Bool) -> [String:String] { var dictionary = [String:String](); dictionary["ELEMENT"] = elementUUID if compact == false { dictionary["label"] = element.wdLabel() dictionary["type"] = element.wdType() } return dictionary } private static func getResponseFromDictionary(_ dictionary:[String:String]) -> HttpResponse { return XCTestWDResponse.response(session:nil, value:JSON(dictionary)) } }
true
df1f973ef57c39fd7c98f08226a4154f10053d12
Swift
Tap-Payments/goSellSDK-iOS
/goSellSDK/Core/UI/Internal/Extensions/EditableTextInsetsTextField+Additions.swift
UTF-8
799
2.578125
3
[ "MIT" ]
permissive
// // EditableTextInsetsTextFieldV2.swift // goSellSDK // // Copyright © 2019 Tap Payments. All rights reserved. // import class EditableTextInsetsTextFieldV2.EditableTextInsetsTextField internal extension EditableTextInsetsTextField { // MARK: - Internal - // MARK: Properties var localizedClearButtonPosition: EditableTextInsetsTextField.ClearButtonPosition { get { return self.clearButtonPosition } set { let ltr = LocalizationManager.shared.layoutDirection == .leftToRight var desiredPosition: EditableTextInsetsTextField.ClearButtonPosition switch newValue { case .left: desiredPosition = ltr ? .left : .right case .right: desiredPosition = ltr ? .right : .left } self.clearButtonPosition = desiredPosition } } }
true
e3407e1c0d342ca3a563c489d8f9badc2d2af393
Swift
vblagoi/hw4
/Homework4/Homework4/ViewController.swift
UTF-8
4,167
2.703125
3
[]
no_license
// // ViewController.swift // Homework4 // // Created by Вова Благой on 21.01.2021. // import UIKit class ViewController: UIViewController { var storage = Storage() private var cellsData: [String: Double] = [:] @IBOutlet weak var cityTextField: UITextField! @IBOutlet weak var addCityButton: UIButton! private let weatherCollectionView: UICollectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) override func viewDidLoad() { super.viewDidLoad() setupViews() setupLayouts() } private func setupViews() { view.backgroundColor = #colorLiteral(red: 0.9254694581, green: 0.9256245494, blue: 0.9254490733, alpha: 1) view.addSubview(weatherCollectionView) weatherCollectionView.dataSource = self weatherCollectionView.delegate = self weatherCollectionView.register(WeatherCollectionViewCell.self, forCellWithReuseIdentifier: WeatherCollectionViewCell.reuseID) updateCellsData() } private func setupLayouts() { weatherCollectionView.translatesAutoresizingMaskIntoConstraints = false weatherCollectionView.backgroundColor = #colorLiteral(red: 0.9254694581, green: 0.9256245494, blue: 0.9254490733, alpha: 1) // Layout constraints for `weatherCollectionView` NSLayoutConstraint.activate([ weatherCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor), weatherCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor), weatherCollectionView.topAnchor.constraint(equalTo: addCityButton.bottomAnchor, constant: 40), weatherCollectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } private func updateCellsData() { for city in storage.citys { let parse = CityWeatherParse() parse.parseCurrentTemperature(city: city, temperatureCompletionHandler: { temp, error in self.cellsData[city] = temp DispatchQueue.main.async { self.weatherCollectionView.reloadData() } }) } } @IBAction func addCityButton(_ sender: Any) { if cityTextField.text! == "" { showAlert() return } storage.addCity(city: cityTextField.text!) cityTextField.text = "" updateCellsData() } func showAlert() { let alert = UIAlertController(title: "Attention", message: "Enter city", preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return storage.citys.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WeatherCollectionViewCell.reuseID, for: indexPath) as! WeatherCollectionViewCell cell.cityName.text = storage.citys[indexPath.row] if let temp = cellsData[storage.citys[indexPath.row]] { cell.cityTemperature.text = String(temp) + " C" } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let vc = storyboard?.instantiateViewController(identifier: "DetailsViewController") as! DetailsViewController vc.name = storage.citys[indexPath.row] self.navigationController?.pushViewController(vc, animated: true) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 300, height: 100) } }
true
a8c836bd71ad2be792853de6e0a62ee192b55537
Swift
iTh1nk/billbook-swift
/Shared/ViewModels/UserViewModel.swift
UTF-8
1,309
2.65625
3
[ "MIT" ]
permissive
// // UserViewModel.swift // Billbook-Swift // // Created by Chao Feng on 1/2/21. // import Foundation import SwiftUI class UserViewModel: ObservableObject { // @EnvironmentObject var enUser: EnUser // // func setEnUser(token: String) { // enUser.enUsername = try! decode(jwtToken: token)["username"] ?? "" // UserDefaults.standard.set(enUser.enUsername, forKey: "Username") // } // // func decode(jwtToken jwt: String) throws -> [String: String] { // // enum DecodeErrors: Error { // case badToken // case other // } // // func base64Decode(_ base64: String) throws -> Data { // let padded = base64.padding(toLength: ((base64.count + 3) / 4) * 4, withPad: "=", startingAt: 0) // guard let decoded = Data(base64Encoded: padded) else { // throw DecodeErrors.badToken // } // return decoded // } // // func decodeJWTPart(_ value: String) throws -> [String: String] { // let bodyData = try base64Decode(value) // let json = try JSONSerialization.jsonObject(with: bodyData, options: []) // guard let payload = json as? [String: String] else { // throw DecodeErrors.other // } // return payload // } // // let segments = jwt.components(separatedBy: ".") // return try decodeJWTPart(segments[1]) // } }
true
f93f574180a89fdf7123a463354da3d3b4ffd05d
Swift
fengweijp/SwiftQ
/Sources/EnqueueingBox.swift
UTF-8
535
2.71875
3
[ "MIT" ]
permissive
// // EnqueueingBox.swift // SwiftQ // // Created by John Connolly on 2017-08-09. // // import Foundation struct EnqueueingBox { let uuid: String let queue: String let value: Data } extension EnqueueingBox { init(_ chain: Chain) throws { self.uuid = chain.uuid self.queue = "default" self.value = try chain.serialized() } init(_ task: Task) throws { self.uuid = task.uuid self.queue = task.queue self.value = try task.serialized() } }
true
98154b45e49d412cd002c03efbd62506c7674040
Swift
zakiyamaaaaa/excellent-project
/swift/prototype02/prototype02/NearUserView.swift
UTF-8
1,731
2.53125
3
[]
no_license
// // NearUserView.swift // MainViewWithFunction05 // // Created by shoichiyamazaki on 2017/04/24. // Copyright © 2017年 shoichiyamazaki. All rights reserved. // import Foundation import UIKit class NearUserView{ var userInfoNameLabel:UILabel var myView:UIView var myImageView:UIImageView var numberOfPage:Int init(frame:CGRect,page:Int) { myView = UIView(frame: frame) myView.layer.borderWidth = 1 myView.layer.shadowOffset = CGSize(width: 0, height: 0) myView.layer.masksToBounds = false myView.layer.shadowColor = UIColor.darkGray.cgColor myView.layer.cornerRadius = 10 myView.layer.shadowOpacity = 0.8 myView.backgroundColor = UIColor.white let userImageViewHeight = frame.height/4*3 let userImageViewWidth = frame.width/10*9 let userViewHeight = frame.height let userViewWidth = frame.width myImageView = UIImageView(frame: CGRect(x: (userViewWidth-userImageViewWidth)/2, y: 10, width: userImageViewWidth, height: userImageViewHeight)) myImageView.layer.borderWidth = 1 myImageView.layer.borderColor = UIColor.darkGray.cgColor myView.addSubview(myImageView) let userInfoLabelHeight = (userViewHeight - userImageViewHeight)/5 let userInfoLabelWidth = userImageViewWidth let userInfoLabelFrame = CGRect(x: (userViewWidth-userImageViewWidth)/2, y: userImageViewHeight/17*18, width: userInfoLabelWidth, height: userInfoLabelHeight) userInfoNameLabel = UILabel(frame: userInfoLabelFrame) myView.addSubview(userInfoNameLabel) self.numberOfPage = page } }
true
9d4f2e7deb090cec99ca0a1ac1e509366d8c3cd8
Swift
jairobbo/SameBoat
/Engine2/Game/Cloud.swift
UTF-8
2,053
2.53125
3
[]
no_license
import MetalKit class Cloud: Node, Renderable, Floating, Equatable { var index: Int = 0 static var cloudSpeed: Float = 0.03 var thunder: Bool = true { didSet { if thunder { DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.thunder = false } } } } override init() { super.init() let lightning = Lightning() lightning.parent = self children.append(lightning) } func render(encoder: MTLRenderCommandEncoder) { time += Double(1)/Double(Renderer.fps) Renderer.uniforms.modelMatrix = matrix_identity_float4x4 position.z -= Cloud.cloudSpeed for child in children { let picknumber = Int(arc4random_uniform(750)) if picknumber == 0 { let strikes = Int(arc4random_uniform(6) + 1) (child as! Lightning).strikes = strikes if !Boat.isSinking{ Game.adjustHardness(amount: Float(strikes)/50) } } (child as! Renderable).render(encoder: encoder) } Renderer.uniforms.modelMatrix = float4x4(translation: position) * float4x4(rotation: rotation) encoder.setRenderPipelineState(Renderer.cloudPipelineState) encoder.setVertexBuffer(Renderer.cloudMeshes[index].vertexBuffers[0].buffer, offset: 0, index: 0) encoder.setVertexBytes(&Renderer.uniforms, length: MemoryLayout<Uniforms>.stride, index: 1) guard let coinSubmesh = Renderer.cloudMeshes[index].submeshes.first else { return } encoder.drawIndexedPrimitives(type: coinSubmesh.primitiveType, indexCount: coinSubmesh.indexCount, indexType: coinSubmesh.indexType, indexBuffer: coinSubmesh.indexBuffer.buffer, indexBufferOffset: coinSubmesh.indexBuffer.offset) } static func == (lhs: Cloud, rhs: Cloud) -> Bool { return lhs.position.x == rhs.position.x } }
true
6033da4b556cf1594585bc84a01d77e83db01e9b
Swift
masonmark/Mason.swift
/Tests/MasonTests/TextReplacerTests.swift
UTF-8
4,197
2.90625
3
[]
no_license
// TextReplacerTests.swift Created by mason on 2016-08-15. Copyright © 2016 MASON MARK (.COM). All rights reserved. #if !os(Linux) import XCTest @testable import Mason import Foundation class TextReplacerTests: TestCase { let before: [String:String] = [ "test1.txt" : "What I like about the cloud is that the cloud likes me.\nWow, the cloud", "test2.japanese" : "韓国に行って、キムチを食えばどう?\nいいよ。", "test3.txt" : "Emoji: 🔥. Slaymoji: 🂋" ] let after: [String:String] = [ "test1.txt" : "What I like about my butt is that my butt likes me.\nWow, my butt", "test2.japanese" : "メキシコに行って、タコスを食えばどう?\nだめよ。", "test3.txt" : "Emoji: 💀. Slaymoji: ⌘" ] var dir = URL(fileURLWithPath: "/this/will/be/replaced") override func setUp() { dir = temporaryDirectoryURL().appendingPathComponent(UUID().uuidString) do { try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: nil) for (filename, text) in before { try text.write(to: dir.appendingPathComponent(filename), atomically: true, encoding: .utf8) } } catch { die("can't write text files") } } func readFiles() -> [String:String] { var result: [String:String] = [:] for filename in after.keys { let url = dir.appendingPathComponent(filename) if let fileContents = try? String(contentsOf: url) { result[filename] = fileContents } } return result } func test_basic() { let tr = TextReplacer() XCTAssertNil( tr.replaceOccurences(of: "the cloud", with: "my butt", directory: dir) ) XCTAssertNil( tr.replaceOccurences(of: "韓国", with: "メキシコ", directory: dir) ) XCTAssertNil( tr.replaceOccurences(of: "キムチ", with: "タコス", directory: dir) ) XCTAssertNil( tr.replaceOccurences(of: "いい", with: "だめ", directory: dir) ) XCTAssertNil( tr.replaceOccurences(of: "🔥", with: "💀", directory: dir) ) XCTAssertNil( tr.replaceOccurences(of: "🂋", with: "⌘", directory: dir) ) let actual = readFiles() let expected = after for (filename) in expected.keys { XCTAssertEqual(actual[filename],expected[filename]) } } func test_with_file_extension_filter() { let tr = TextReplacer() let extensions = ["txt", "nonexistent"] XCTAssertNil( tr.replaceOccurences(of: "the cloud", with: "my butt", directory: dir, extensions: extensions) ) XCTAssertNil( tr.replaceOccurences(of: "韓国", with: "メキシコ", directory: dir, extensions: extensions) ) XCTAssertNil( tr.replaceOccurences(of: "キムチ", with: "タコス", directory: dir, extensions: extensions) ) XCTAssertNil( tr.replaceOccurences(of: "いい", with: "だめ", directory: dir, extensions: extensions) ) XCTAssertNil( tr.replaceOccurences(of: "🔥", with: "💀", directory: dir, extensions: extensions) ) XCTAssertNil( tr.replaceOccurences(of: "🂋", with: "⌘", directory: dir, extensions: extensions) ) let actual = readFiles() let expected = [ "test1.txt" : "What I like about my butt is that my butt likes me.\nWow, my butt", "test2.japanese" : "韓国に行って、キムチを食えばどう?\nいいよ。", // should not be processed "test3.txt" : "Emoji: 💀. Slaymoji: ⌘" ] for (filename) in expected.keys { XCTAssertEqual(actual[filename],expected[filename]) } } } extension TextReplacerTests { static var allTests : [(String, (TextReplacerTests) -> () throws -> Void)] { return [ ("test_basic", test_basic), ("test_with_file_extension_filter", test_with_file_extension_filter), ] } } #endif // !os(Linux)
true
3ebcf15edc16376c033a2e1420c51230830a9bd9
Swift
viniciusml/Omnifi
/Omnifi/Model/Restaurant.swift
UTF-8
3,082
2.546875
3
[]
no_license
// // Restaurant.swift // Omnifi // // Created by Vinicius Leal on 31/08/19. // Copyright © 2019 Vinicius Leal. All rights reserved. // import Foundation // MARK: - RestaurantElement struct RestaurantElement: Codable { let name: String let enableOrderAhead: Enable let clickAndCollect: Bool let ccVersion: CcVersion let voucherBand: VoucherBand let additional, bookingID, city: String let country: Country let fax, latitude, longitude, openFriday: String let openMonday, openSaturday, openSunday, openThursday: String let openTuesday, openWednesday, postalCode: String let region: Region let siteID, street, telephone, title: String let url: String let taxonomy, body: String let zonalSiteID: String? let deliveryLink: String let deliverooDirectLink, uberEatsDirectLink, justEatDirectlink: String? let enableDAT: Enable? let disableBookings: Bool? let enableClickAndCollect: Enable? enum CodingKeys: String, CodingKey { case name, enableOrderAhead, clickAndCollect, ccVersion, voucherBand, additional case bookingID = "booking_id" case city, country, fax, latitude, longitude case openFriday = "open_friday" case openMonday = "open_monday" case openSaturday = "open_saturday" case openSunday = "open_sunday" case openThursday = "open_thursday" case openTuesday = "open_tuesday" case openWednesday = "open_wednesday" case postalCode = "postal_code" case region case siteID = "site_id" case street, telephone, title, url, taxonomy, body case zonalSiteID = "zonalSiteId" case deliveryLink = "delivery_link" case deliverooDirectLink, uberEatsDirectLink, justEatDirectlink, enableDAT, disableBookings, enableClickAndCollect } } enum CcVersion: String, Codable { case v2 = "v2" } // MARK: - Country enum Country: String, Codable { case countryUK = "UK" case empty = "" case gb = "gb" case uk = "uk" } // MARK: - Enable enum Enable: String, Codable { case no = "no" case yes = "yes" } // MARK: - Region enum Region: String, Codable, CustomStringConvertible { case eastMidlands = "East Midlands" case eastOfEngland = "East of England" case london = "London" case northEast = "North East" case northWest = "North West" case northernIreland = "Northern Ireland" case regionNorthEast = "north east" case regionYorkshireAndTheHumber = "Yorkshire And The Humber" case scotland = "Scotland" case southEast = "South East" case southWest = "South West" case wales = "Wales" case westMidlands = "West Midlands" case yorkshireAndTheHumber = "Yorkshire and The Humber" var description: String { return self.rawValue } } // MARK: - VoucherBand enum VoucherBand: String, Codable { case none = "NONE" case siteBandOne = "SITE_BAND_ONE" case siteBandThree = "SITE_BAND_THREE" case siteBandTwo = "SITE_BAND_TWO" } typealias Restaurant = [RestaurantElement]
true
f2c1062cd643396292e65cf68f64f8a55ba6aee3
Swift
gittraverse/User-Interface-V1
/Udemy IOS Development/Introduction.playground/Contents.swift
UTF-8
559
4.5625
5
[]
no_license
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground"; print (str); //declare 2 variables a and b var a = 5; var b = 1; print(a+b); if(a+b > 6) { print("true"); } else { print("false"); } class Person { var name:String = "Initial name" init() { self.sayCheese() } func sayCheese() { print("Cheese") } } var firstPerson = Person() firstPerson.name = "Alice" firstPerson.name var secondPerson = Person() secondPerson.name = "Bob" firstPerson.name
true
7f3995188877d9eb651f5f1ebd2e2c06a6a68df3
Swift
cocuroci/marvel
/marvel/marvelTests/Scenes/List/ListPresenterTests.swift
UTF-8
4,538
2.765625
3
[]
no_license
import XCTest @testable import marvel private final class ListViewControllerSpy: ListDisplaying { // MARK: - displayCharacters private(set) var displayCharactersCount = 0 private(set) var characters: [Character]? func displayCharacters(_ characters: [Character]) { displayCharactersCount += 1 self.characters = characters } // MARK: - displayLoader private(set) var displayLoaderCount = 0 func displayLoader() { displayLoaderCount += 1 } // MARK: - displayFeedbackView private(set) var displayFeedbackViewCount = 0 private(set) var textFeedbackView: String? private(set) var imageNameFeedbackView: String? func displayFeedbackView(text: String, imageName: String) { displayFeedbackViewCount += 1 textFeedbackView = text imageNameFeedbackView = imageName } // MARK: - removeFeedbackView private(set) var removeFeedbackViewCount = 0 func removeFeedbackView() { removeFeedbackViewCount += 1 } // MARK: - displayEmptyView private(set) var displayEmptyViewCount = 0 private(set) var textDisplayEmptyView: String? private(set) var imageNameDisplayEmptyView: String? func displayEmptyView(text: String, imageName: String) { displayEmptyViewCount += 1 textDisplayEmptyView = text imageNameDisplayEmptyView = imageName } // MARK: - hideLoader private(set) var hideLoaderCount = 0 func hideLoader() { hideLoaderCount += 1 } } final class ListCoordinatorSpy: ListCoordinating { var viewController: UIViewController? // MARK: - perform private(set) var performCount = 0 private(set) var action: ListAction? func perform(action: ListAction) { performCount += 1 self.action = action } } final class ListPresenterTests: XCTestCase { private let coordinatorSpy = ListCoordinatorSpy() private let viewControllerSpy = ListViewControllerSpy() private lazy var sut: ListPresenting = { let presenter = ListPresenter(coordinator: coordinatorSpy) presenter.viewController = viewControllerSpy return presenter }() func testPresentCharacters_ShouldDisplayCharacters() { let mocked = [Character(id: 1, name: "name", description: nil, thumbnail: nil)] sut.presentCharacters(mocked) XCTAssertEqual(viewControllerSpy.displayCharactersCount, 1) XCTAssertEqual(viewControllerSpy.characters?.count, 1) } func testPresentLoader_ShouldDisplayLoader() { sut.presentLoader() XCTAssertEqual(viewControllerSpy.displayLoaderCount, 1) } func testHideLoader_ShouldHideLoader() { sut.hideLoader() XCTAssertEqual(viewControllerSpy.hideLoaderCount, 1) } func testPresentNoInternetView_ShouldDisplayFeedbackView() { sut.presentNoInternetView() XCTAssertEqual(viewControllerSpy.displayFeedbackViewCount, 1) XCTAssertEqual(viewControllerSpy.textFeedbackView, "Sem conexão") XCTAssertEqual(viewControllerSpy.imageNameFeedbackView, "wifi.slash") } func testPresentErrorView_ShouldDisplayFeedbackView() { sut.presentErrorView() XCTAssertEqual(viewControllerSpy.displayFeedbackViewCount, 1) XCTAssertEqual(viewControllerSpy.textFeedbackView, "Ops! Falha na requisição") XCTAssertEqual(viewControllerSpy.imageNameFeedbackView, "exclamationmark.circle") } func testPresentEmptyResultView_ShouldDisplayEmptyView() { sut.presentEmptyResultView() XCTAssertEqual(viewControllerSpy.displayEmptyViewCount, 1) XCTAssertEqual(viewControllerSpy.textDisplayEmptyView, "Resultado não encontrado") XCTAssertEqual(viewControllerSpy.imageNameDisplayEmptyView, "exclamationmark.circle") } func testRemoveFeedbackView_ShouldRemoveFeedbackView() { sut.removeFeedbackView() XCTAssertEqual(viewControllerSpy.removeFeedbackViewCount, 1) } func testDidNextStep_ShouldPassActionToCoordinator() { let action: ListAction = .detail(character: Character(id: 1, name: "name", description: nil, thumbnail: nil), delegate: nil) sut.didNextStep(action: action) XCTAssertEqual(coordinatorSpy.performCount, 1) XCTAssertEqual(coordinatorSpy.action, action) } }
true
26f67a3052a044b44d9e7e66d631ea26c0e31044
Swift
LeaderQiu/SwiftWeibo
/HMWeibo04/HMWeibo04/Classes/BusinessModel/StatusesData.swift
UTF-8
15,379
2.84375
3
[ "MIT" ]
permissive
// // StatusesData.swift // HMWeibo04 // // Created by apple on 15/3/5. // Copyright (c) 2015年 heima. All rights reserved. // import UIKit /** 关于业务模型 - 专门处理"被动"的业务,模型类永远不知道谁会在什么时候调用它! - 准备好跟数据模型相关的数据 */ /// 加载微博数据 URL private let WB_Home_Timeline_URL = "https://api.weibo.com/2/statuses/home_timeline.json" /// 微博数据列表模型 class StatusesData: NSObject, DictModelProtocol { /// 微博记录数组 var statuses: [Status]? /// 微博总数 var total_number: Int = 0 /// 未读数辆 var has_unread: Int = 0 static func customClassMapping() -> [String: String]? { return ["statuses": "\(Status.self)"] } /// 刷新微博数据 - 专门加载网络数据以及错误处理的回调 /// 一旦加载成功,负责字典转模型,回调传回转换过的模型数据 /// 增加一个 max_id 的参数,就能够支持上拉加载数据,max_id 如果等于 0,就是刷新最新的数据! /// maxId: Int = 0,指定函数的参数默认数值,如果不传,就是 0 /// topId: 是视图控制器中 statues 的第一条微博的 id,topId 和 maxId 之间就是 statuses 中的所有数据 class func loadStatus(maxId: Int = 0, topId: Int, completion: (data: StatusesData?, error: NSError?)->()) { // TODO: - 上拉刷新,判断是否可以从本地缓存加载数据 if maxId > 0 { // 检查本地数据,如果存在本地数据,直接返回 if let result = checkLocalData(maxId) { println("加载本地数据...") // 从本地加载了数据,直接回调 let data = StatusesData() data.statuses = result completion(data: data, error: nil) return } } // 以下是从网络加载数据 let net = NetworkManager.sharedManager if let token = AccessToken.loadAccessToken()?.access_token { let params = ["access_token": token, "max_id": "\(maxId)"] // 发送网络异步请求 net.requestJSON(.GET, WB_Home_Timeline_URL, params) { (result, error) -> () in if error != nil { // 错误处理 completion(data: nil, error: error!) return } // 字典转模型 var modelTools = DictModelManager.sharedManager var data = modelTools.objectWithDictionary(result as! NSDictionary, cls: StatusesData.self) as? StatusesData // 保存微博数据 self.saveStatusData(data?.statuses) // 如果 maxId > 0,表示是上拉刷新,将 maxId & topId 之间的所有数据的 refresh 状态修改成 1 self.updateRefreshState(maxId, topId: topId) // 如果有下载图像的 url,就先下载图像 if let urls = StatusesData.pictureURLs(data?.statuses) { net.downloadImages(urls) { (_, _) -> () in // 回调通知视图控制器刷新数据 completion(data: data, error: nil) } } else { // 如果没有要下载的图像,直接回调 -> 将模型通知给视图控制器 completion(data: data, error: nil) } } } } /// 检查本地数据,判断本地是否存在小于 maxId 的连续数据 /// 如果存在,直接返回本地的数据 /// 如果不存在,返回 nil,调用方加载网络数据 class func checkLocalData(maxId: Int) -> [Status]? { // 1. 判断 refresh 标记 let sql = "SELECT count(*) FROM T_Status \n" + "WHERE id = (\(maxId) + 1) AND refresh = 1" if SQLite.sharedSQLite.execCount(sql) == 0 { return nil } println("应该加载本地数据") // 生成应用程序需要的结果集合直接返回即可! // 结果集合中包含微博的数组,同时,需要把分散保存在数据表中的数据,再次整合! let resultSQL = "SELECT id, text, source, created_at, reposts_count, \n" + "comments_count, attitudes_count, userId, retweetedId FROM T_Status \n" + "WHERE id < \(maxId) \n" + "ORDER BY id DESC \n" + "LIMIT 20" // 实例化微博数据数组 var statuses = [Status]() /// 查询返回结果集合 let recordSet = SQLite.sharedSQLite.execRecordSet(resultSQL) /// 遍历数组,建立目标微博数据数组 for record in recordSet { statuses.append(Status(record: record as! [AnyObject])) } if statuses.count == 0 { return nil } else { return statuses } } /// 更新 maxId & topId 之间记录的刷新状态 class func updateRefreshState(maxId: Int, topId: Int) { let sql = "UPDATE T_Status SET refresh = 1 \n" + "WHERE id BETWEEN \(maxId) AND \(topId);" SQLite.sharedSQLite.execSQL(sql) } /// 保存微博数据 class func saveStatusData(statuses: [Status]?) { if statuses == nil { return } // 保存数据 // 0. 开启事务 // 关于事务,需要注意: // 1> BEGIN TRANSACTION & COMMIT TRANSACTION 要配对出现 // 2> 如果出现错误,可以 ROLLBACK 回滚,注意不要重复 ROLLBACK // 3> 在 SQL 操作中,默认都会有一隐含的事务,只是执行一句话,结果就是 true/false // 用于批量数据插入的! // 不要在多个线程中,同时对数据库进行读写操作!可以创建一个串行队列!把所有数据操作任务,顺序放在队列中执行即可! // SQLite 本身的性能已经很好了,大量数据操作不会占用很长的时间! SQLite.sharedSQLite.execSQL("BEGIN TRANSACTION") // 1. 遍历微博数组 for s in statuses! { // 1. 配图记录(保存谁,谁负责) if !StatusPictureURL.savePictures(s.id, pictures: s.pic_urls) { // 一旦出现错误就“回滚” - 放弃所有的操作 println("配图记录插入错误") SQLite.sharedSQLite.execSQL("ROLLBACK TRANSACTION") break } // 2. 用户记录 - 由于不能左右服务器返回的数据 if s.user != nil { if !s.user!.insertDB() { println("插入用户数据错误") SQLite.sharedSQLite.execSQL("ROLLBACK TRANSACTION") break } } // 3. 微博记录 if !s.insertDB() { println("插入微博数据错误") SQLite.sharedSQLite.execSQL("ROLLBACK TRANSACTION") break } // 4. 转发微博的记录(用户/配图) if s.retweeted_status != nil { // 存在转发微博 // 保存转发微博 if !s.retweeted_status!.insertDB() { println("插入转发微博数据错误") SQLite.sharedSQLite.execSQL("ROLLBACK TRANSACTION") break } } } // 5. 提交事务 SQLite.sharedSQLite.execSQL("COMMIT TRANSACTION") } /// 取出给定的微博数据中所有图片的 URL 数组 /// /// :param: statuses 微博数据数组,可以为空 /// /// :returns: 微博数组中的 url 完整数组,可以为空 class func pictureURLs(statuses: [Status]?) -> [String]? { // 如果数据为空直接返回 if statuses == nil { return nil } // 遍历数组 var list = [String]() for status in statuses! { // 继续遍历 pic_urls(原创微博的图片) if let urls = status.pictureUrls { for pic in urls { list.append(pic.thumbnail_pic!) } } } if list.count > 0 { return list } else { return nil } } } /// 微博模型 class Status: NSObject, DictModelProtocol { /// 微博创建时间 var created_at: String? /// 微博ID var id: Int = 0 /// 微博信息内容 var text: String? /// 微博来源 var source: String? /// 去掉 href 的来源字符串 var sourceStr: String { return source?.removeHref() ?? "" } /// 转发数 var reposts_count: Int = 0 /// 评论数 var comments_count: Int = 0 /// 表态数 var attitudes_count: Int = 0 /// 配图数组 var pic_urls: [StatusPictureURL]? /// 要显示的配图数组 /// 如果是原创微博,就使用 pic_urls /// 如果是转发微博,使用 retweeted_status.pic_urls /// 如果一个属性是只读的,只有 get,没有 set,get 可以省略 var pictureUrls: [StatusPictureURL]? { if retweeted_status != nil { return retweeted_status?.pic_urls } else { return pic_urls } } /// 所有大图的 URL - 计算属性 var largeUrls: [String]? { // 可以使用 kvc 直接拿值 var urls = self.valueForKeyPath("pictureUrls.large_pic") as? NSArray return urls as? [String] } /// 用户信息 var user: UserInfo? /// 转发微博,如果有就是转发微博,如果没有就是原创微博 var retweeted_status: Status? static func customClassMapping() -> [String : String]? { return ["pic_urls": "\(StatusPictureURL.self)", "user": "\(UserInfo.self)", "retweeted_status": "\(Status.self)",] } /// 使用数据库的结果集合,实例化微博数据 /// 构造函数,实例化并且返回对象 init(record: [AnyObject]) { // id, text, source, created_at, reposts_count, comments_count, attitudes_count, userId, retweetedId id = record[0] as! Int text = record[1] as? String source = record[2] as? String created_at = record[3] as? String reposts_count = record[4] as! Int comments_count = record[5] as! Int attitudes_count = record[6] as! Int // 用户对象 let userId = record[7] as! Int user = UserInfo(pkId: userId) // 转发微博对象 let retId = record[8] as! Int // 如果有转发数据 if retId > 0 { retweeted_status = Status(pkId: retId) } // 配图数组 pic_urls = StatusPictureURL.pictureUrls(id) } /// 使用数据库的主键实例化对象 /// convenience 不是主构造函数,简化的构造函数,必须调用默认的构造函数 convenience init(pkId: Int) { // 使用主键查询数据库 let sql = "SELECT id, text, source, created_at, reposts_count, \n" + "comments_count, attitudes_count, userId, retweetedId FROM T_Status \n" + "WHERE id = \(pkId) " let record = SQLite.sharedSQLite.execRow(sql) self.init(record: record!) } // 保存微博数据 func insertDB() -> Bool { // 提示:如果 Xcode 6.3 Bata 2/3 直接写 ?? 会非常非常慢 let userId = user?.id ?? 0 let retId = retweeted_status?.id ?? 0 // 判断数据是否已经存在,如果存在就不再插入 var sql = "SELECT count(*) FROM T_Status WHERE id = \(id);" if SQLite.sharedSQLite.execCount(sql) > 0 { return true } // 之所以只使用 INSERT,是因为 INSERT AND REPLACE 会在更新数据的时候,直接将 refresh 重新设置为 0 sql = "INSERT INTO T_Status \n" + "(id, text, source, created_at, reposts_count, comments_count, attitudes_count, userId, retweetedId) \n" + "VALUES \n" + "(\(id), '\(text!)', '\(source!)', '\(created_at!)', \(reposts_count), \(comments_count), \(attitudes_count), \(userId), \(retId));" return SQLite.sharedSQLite.execSQL(sql) } } /// 微博配图模型 class StatusPictureURL: NSObject { /// 缩略图 URL var thumbnail_pic: String? { didSet { // 生成大图的 URL,将 thumbnail_pic 替换成 large // 1. 定义一个字符串 var str = thumbnail_pic! as NSString // 2. 直接替换字符串 large_pic = str.stringByReplacingOccurrencesOfString("thumbnail", withString: "large") } } /// 大图 URL var large_pic: String? /// 使用数据库结果集合实例化对象 init(record: [AnyObject]) { thumbnail_pic = record[0] as? String } /// 如果要返回对象的数组,可以使用类函数 /// 给定一个微博代号,返回改微博代号对应配图数组,0~9张配图 class func pictureUrls(statusId: Int) -> [StatusPictureURL]? { let sql = "SELECT thumbnail_pic FROM T_StatusPic WHERE status_id = \(statusId)" let recordSet = SQLite.sharedSQLite.execRecordSet(sql) // 实例化数组 var list = [StatusPictureURL]() for record in recordSet { list.append(StatusPictureURL(record: record as! [AnyObject])) } if list.count == 0 { return nil } else { return list } } /// 插入到数据库 func insertDB(statusId: Int) -> Bool { let sql = "INSERT INTO T_StatusPic (statusId, thumbnail_pic) VALUES (\(statusId), '\(thumbnail_pic!)');" return SQLite.sharedSQLite.execSQL(sql) } /// 将配图数组保存到数据库 class func savePictures(statusId: Int, pictures: [StatusPictureURL]?) -> Bool { if pictures == nil { // 没有图需要保存,就继续后续的工作 return true } // 为了避免图片数据会被重复插入,在插入数据前需要先判断一下 // 判断数据库中是否已经存在 statsId = statusId 图片记录! let sql = "SELECT count(*) FROM T_StatusPic WHERE statusId = \(statusId);" if SQLite.sharedSQLite.execCount(sql) > 0 { return true } // 更新微博图片 for pic in pictures! { // 一旦保存图片失败 if !pic.insertDB(statusId) { // 直接返回 return false } } return true } }
true
816076a97118edb5203a03ffde78fc2b7928e835
Swift
johnpitts/ios-sprint-challenge-experiences
/ExperiencesPractice/ExperiencesPractice/View Controllers/VideoCaptureViewController.swift
UTF-8
6,282
2.515625
3
[]
no_license
// // VideoCaptureViewController.swift // ExperiencesPractice // // Created by John Pitts on 7/12/19. // Copyright © 2019 johnpitts. All rights reserved. // import UIKit import AVFoundation class VideoCaptureViewController: UIViewController { lazy private var captureSession = AVCaptureSession() lazy private var fileOutput = AVCaptureMovieFileOutput() private var player: AVPlayer! @IBOutlet weak var cameraView: CameraPreviewView! @IBOutlet weak var recordButton: UIButton! var experienceMapViewController = ExperiencesMapViewController() var videoURL: URL? // { // didSet { // updateViews() // } // } var experience: Experience? override func viewDidLoad() { super.viewDidLoad() let status = AVCaptureDevice.authorizationStatus(for: .video) switch status { case .notDetermined: AVCaptureDevice.requestAccess(for: .video) { (granted) in if granted == false { fatalError("Please request user enable camera in Settings > Privacy") } DispatchQueue.main.async { self.showCamera() } } case .restricted: // we don't have permission from the user because of parental controls fatalError("Please inform the user they cannot use app due to parental restrictions") case .denied: // we asked for permission, but the user said no fatalError("Please request user to enable camera usage in Settings > Privacy") case .authorized: // we asked for permission and they said yes. showCamera() @unknown default: fatalError() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) captureSession.startRunning() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) captureSession.stopRunning() } func showCamera() { let camera = bestCamera() guard let cameraInput = try? AVCaptureDeviceInput(device: camera) else { fatalError("Can't create input from camera") } // Setup inputs if captureSession.canAddInput(cameraInput) { captureSession.addInput(cameraInput) } guard let microphone = AVCaptureDevice.default(for: .audio) else { fatalError("Can't find microphone") } guard let microphoneInput = try? AVCaptureDeviceInput(device: microphone) else { fatalError("Can't create input from microphone") } if captureSession.canAddInput(microphoneInput) { captureSession.addInput(microphoneInput) } // Setup outputs if captureSession.canAddOutput(fileOutput) { captureSession.addOutput(fileOutput) } if captureSession.canSetSessionPreset(.hd1920x1080) { captureSession.canSetSessionPreset(.hd1920x1080) } captureSession.commitConfiguration() cameraView.session = captureSession } private func bestCamera() -> AVCaptureDevice { if let device = AVCaptureDevice.default(.builtInDualCamera, for: .video, position: .back) { return device } if let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) { return device } fatalError("No cameras exist - you're probably running on the simulator") } @IBAction func recordButtonTapped(_ sender: Any) { if fileOutput.isRecording { fileOutput.stopRecording() experience?.videoRecording = videoURL updateViews() } else { fileOutput.startRecording(to: newRecordingURL(), recordingDelegate: self) } } func newRecordingURL() -> URL { let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let name = UUID().uuidString print("name: \(name)") let videoURL = documentsDirectory.appendingPathComponent(name).appendingPathExtension("mov") print("Url: \(videoURL)") return videoURL } func updateViews() { if fileOutput.isRecording { recordButton.setImage(UIImage(named: "Stop"), for: .normal) recordButton.tintColor = UIColor.blue } else { recordButton.setImage(UIImage(named: "Record"), for: .normal) recordButton.tintColor = UIColor.red // my record images never show color, why? } } @IBAction func saveButtonTapped(_ sender: Any) { // use video file to create experience: done in fileOutput extension below guard let lat = experience?.location.latitude, let long = experience?.location.longitude, let image = experience?.image, let audioRecording = experience?.audioRecording, let nam = experience?.name else { return } experienceMapViewController.createExperience(name: nam, image: image, audioRecording: audioRecording, longitude: long, latitude: lat, videoRecording: videoURL!) navigationController?.popToRootViewController(animated: true) } } extension VideoCaptureViewController: AVCaptureFileOutputRecordingDelegate { func fileOutput(_ output: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) { DispatchQueue.main.async { self.updateViews() } } func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) { videoURL = outputFileURL DispatchQueue.main.async { self.updateViews() } } }
true
578f561e44c288e6ae72c2c7a41297acb9b3dbec
Swift
ssamadgh/WWDC-Videos
/UIKit and Animations/WWDC 2013/Customizing Your App's Appearance for iOS 7/Sample_Code/TicTacToeApp_Swift/TicTacToeApp_Swift/TTTAppDelegate.swift
UTF-8
2,439
2.546875
3
[]
no_license
// // AppDelegate.swift // TicTacToeApp_Swift // // Created by Seyed Samad Gholamzadeh on 7/9/18. // Copyright © 2018 Seyed Samad Gholamzadeh. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var profile: TTTProfile! var profileURL: URL = { var url = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) url = url.appendingPathComponent("Profile.ttt") return url }() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. UINavigationBar.appearance().setBackgroundImage(UIImage(named: "navigationBarBackground"), for: .default) UINavigationBar().titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.black] let profileURL = self.profileURL self.profile = self.loadProfile(with: profileURL) self.window = UIWindow(frame: UIScreen.main.bounds) let viewController1 = TTTPlayViewController.viewController(with: self.profile, profileURL: profileURL) let viewController2 = TTTMessagesViewController.viewController(with: self.profile, profileURL: profileURL) let viewController3 = TTTProfileViewController.viewController(with: self.profile, profileURL: profileURL) let tabBarController = UITabBarController() tabBarController.viewControllers = [viewController1, viewController2, viewController3] tabBarController.tabBar.backgroundImage = UIImage(named: "barBackground") self.window!.rootViewController = tabBarController self.updateTintColor() self.window!.makeKeyAndVisible() NotificationCenter.default.addObserver(self, selector: #selector(iconDidChange(_:)), name: NSNotification.Name(rawValue: TTTProfileIconDidChangeNotification), object: nil) return true } func loadProfile(with url: URL) -> TTTProfile { var profile = TTTProfile.profileWithContentsOf(url) if profile == nil { profile = TTTProfile() } return profile! } func updateTintColor() { if self.profile.icon == .X { self.window?.tintColor = UIColor(hue: 0.0, saturation: 1.0, brightness: 1.0, alpha: 1.0) } else { self.window?.tintColor = UIColor(hue: 1.0 / 3.0, saturation: 1.0, brightness: 0.8, alpha: 1.0) } } @objc func iconDidChange(_ notification: Notification) { self.updateTintColor() } }
true
a7679fb94f68c5ece61f9c8e9fe05839882867c3
Swift
gadireddi226/ios_lessons_list
/Books/Characters/CharacterListViewController.swift
UTF-8
4,108
3.046875
3
[]
no_license
// // CharacterListViewController.swift // Books // // Created by Erik Gadireddi on 27.02.2021. // import Foundation import UIKit final class CharacterListViewController: UITableViewController { var characters: [CharacterResponse.Person] = [] override init(style: UITableView.Style) { super.init(style: style) self.title = "Characters" } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") let session = URLSession.shared // you need to sign up and fill this empty string // https://the-one-api.dev/sign-up let token = "" if token == "" { fatalError("token not initialized maybe you need to get one https://the-one-api.dev/sign-up") } let url = URL(string: "https://the-one-api.dev/v2/character")! // create get request with token var request = URLRequest(url: url) request.httpMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.setValue( "Bearer \(token)", forHTTPHeaderField: "Authorization") let dataTask = session.dataTask(with: request) { (data, response, error) in guard let data = data else { return } do { // print(String(decoding: data, as: UTF8.self)) let responseObject = try JSONDecoder().decode(CharacterResponse.self, from: data) self.characters = responseObject.docs.filter{ self.isKnown($0.name) } DispatchQueue.main.async { self.tableView.reloadData() } } catch { print(error) } } dataTask.resume() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return characters.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Reuse or create a cell. //let cell = UITableViewCell() let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = characters[indexPath.row].name return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let character = characters[indexPath.row].id let viewController = CharacterQuotes(character) // first method //navigationController?.pushViewController(viewController, animated: true) // second method let nc = UINavigationController(rootViewController: viewController) present(nc , animated: true, completion: nil) } private func isKnown(_ name: String) -> Bool { let famousCharacters = ["Bofur", "Boromir", "Frodo Baggins", "Gandalf","Galandriel","Gimli","Bilbo Baggins","Saruman", "Legolas","Aragorn II. Elessar"] return famousCharacters.contains(name) } } /* example _id":"5cdbdecb6dc0baeae48cfac6", "death":"NaN", "birth":"NaN", "hair":"NaN", "realm":"NaN", "height":"NaN", "spouse":"Unnamed Wife", "gender":"Male", -- seems to be optional "name":"Galathil", "race":"Elves"} */ struct CharacterResponse: Decodable { struct Person: Decodable { let id: String let death: String? let birth: String? let hair: String let realm: String? let height: String? let spouse: String? let gender: String? let name: String let race: String? enum CodingKeys: String, CodingKey { case id = "_id", death, birth, hair,realm, height, spouse, gender, name,race } } let docs: [Person] }
true
af15f48e1157f23428e15e43dedfe9b3be5638b8
Swift
hasanakoglu/recipe-app-final
/RecipeApp/Views/InstructionCellTableViewCell.swift
UTF-8
1,322
3
3
[]
no_license
// // InstructionCell.swift // RecipeApp // // Created by Hasan Akoglu on 20/02/2018. // Copyright © 2018 ford. All rights reserved. // import UIKit class InstructionCell: UITableViewCell { @IBOutlet var checkmarkButton: UIButton! @IBOutlet var descriptionLabel: UILabel! func configure(_ description: String) { descriptionLabel.text = description } // @IBAction func checkmarkTapped(_ sender: AnyObject) { // shouldStrikeThroughText(!checkmarkButton.isSelected) // } func shouldStrikeThroughText(_ strikeThrough :Bool) { guard let text = descriptionLabel.text else { return } let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: text) checkmarkButton.isAccessibilityElement = false if strikeThrough { descriptionLabel.accessibilityLabel = "Completed: \(text)" attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length)) } else { descriptionLabel.accessibilityLabel = "Uncompleted: \(text)" } checkmarkButton.isSelected = strikeThrough descriptionLabel.attributedText = attributeString } }
true
c584bdd04abab390a07f5eb8f17f0ef5805dc3b2
Swift
KaiCode2/WWDC2015Submission
/Kai Aldag/Kai Aldag/ParagraphCell.swift
UTF-8
530
2.53125
3
[]
no_license
// // ParagraphCell.swift // Kai Aldag // // Created by Kai Aldag on 2015-04-11. // Copyright (c) 2015 Kai Aldag. All rights reserved. // import UIKit class ParagraphCell: UICollectionViewCell { @IBOutlet weak var textLabel: UILabel! override func prepareForReuse() { super.prepareForReuse() textLabel.text = nil textLabel.alpha = 0 } func animateCell() { UIView.animateWithDuration(1.2, animations: { () -> Void in self.textLabel.alpha = 1 }) } }
true
d898dde4bfaff7b178e85c5b10ecfc18895355a7
Swift
FrancisWils/TestRepository-
/Clustering.swift
UTF-8
12,050
2.6875
3
[]
no_license
// // Clustering.swift // clustering // // Created by Vincent on 8/1/16. // Copyright © 2016 Vincent. All rights reserved. // import Foundation import CoreLocation import MapKit class Clustering { var data_dict: [String:Int] = [ "msg_id" : 0, "lat" : 1, "lon" : 2, "tag" : 3 ] var cluster_stack = [Message]() var message_array = [Message]() var radius = Float() var tag_summary_data_dict = [String: Int]() var true_statement1:Bool var true_statement2:Bool var dist_sum:Float var potential_centroid_index = Int() var num_clusters = Int() var distance = Float() var cluster_id = Int() var clustered_message_array = [Message]() var centroid_array = [Message]() var cluster_stacks = [Message]() var workingStack = [Message]() var potential_centroid = Message() init (message_array: [Message], radius: Float) { self.message_array = message_array self.radius = radius self.tag_summary_data_dict = [String: Int]() self.true_statement1 = Bool(false) self.true_statement2 = Bool(false) self.dist_sum = Float() self.num_clusters = Int() self.distance = Float() self.cluster_id = Int() self.clustered_message_array = [Message]() self.centroid_array = [Message]() self.cluster_stacks = [Message]() self.workingStack = [Message]() self.potential_centroid = Message() self.find_clusters_by_tag() self.find_centroids() } func summarize_tags_by_count() { // Error Check /* guard (!self.message_array.isEmpty) else { let rr_error: RR_Error = RR_Error(error_num: 200, error_desc: "Message array is empty") print(rr_error.long_error) return } */ // Read message_array for message in self.message_array { // Increment County By Tag if (self.tag_summary_data_dict[message.tag] != nil) { //print(message.tag, "data dict tag") self.tag_summary_data_dict[message.tag]! += 1 } else { //print(message.tag, "data dict tag") self.tag_summary_data_dict[message.tag] = 1 } } for key in self.tag_summary_data_dict { print("Key:", key) } } func find_clusters_by_tag() { self.summarize_tags_by_count() self.cluster_id = 0 // For each key in tag_summary_data_dict for key in self.tag_summary_data_dict { var message_stack = [Message]() //print("Key:", key) // For each message; check tag and create a message stack // The message_stack is going to be passed to find_clusters() to determine first pass clusters for message in self.message_array { if message.tag == key.0 { message_stack.append(message) // let object = message // print ("Tag - Message:", object.msg_id, object.lat, object.lon, object.tag) } } self.workingStack = message_stack find_clusters(message_stack) } } func find_clusters(message_stack: [Message]) { var stack : [Message] = message_stack print("Stack Count:", stack.count) while (stack.count > 0) { stack = filter_within_radius(stack, radius: self.radius, identifier: self.cluster_id) self.cluster_id += 1 } return } func filter_within_radius(main_working_stack:[Message], radius: Float, identifier: Int) -> [Message] { // print "Remaining:", len(stack) var in_cluster = 0 var out_cluster = 0 var temp_stack = [Message]() // var temp_cluster_stack = [Message]() var row_cntr = 0 var lat1 = Float() var lon1 = Float() var lat2 = Float() var lon2 = Float() // var tag = String() for value in main_working_stack { row_cntr += 1 if row_cntr == 1 { lat1 = value.lat lon1 = value.lon lat2 = lat1 lon2 = lon1 } else { lat2 = value.lat lon2 = value.lon } let distance = self.calculate_distance(lat1, lon1: lon1, lat2: lat2,lon2: lon2) value.cluster_id = identifier self.num_clusters = identifier + 1 value.distance = distance if distance < self.radius { in_cluster += 1 self.clustered_message_array.append(value) // print("Value:", value.msg_id, value.distance) // print "In Cluster:", identifier, lat1, lon1, lat2, lon2, distance, "meters" } else { out_cluster += 1 temp_stack.append(value) //print "Out Cluster:", lat1, lon1, lat2, lon2, distance } // print("In/Out:", in_cluster, out_cluster) // temp_stack contains out_cluster messages } return temp_stack } func calculate_distance(lat1: Float, lon1: Float, lat2: Float, lon2: Float) -> Float { /* CLLocationCoordinate2D { guard let location = value as? NSDictionary, let latitude = (location["lat"] ?? location["latitude"]) as? Double, let longitude = (location["lng"] ?? location["longitude"]) as? Double else { throw MapperError() } */ let pointOne = CLLocationCoordinate2D(latitude: Double(lat1), longitude: Double(lon1)) let pointTwo = CLLocationCoordinate2D(latitude: Double(lat2), longitude: Double(lon2)) let mapPoint1 = MKMapPointForCoordinate(pointOne) let mapPoint2 = MKMapPointForCoordinate(pointTwo) let distance = MKMetersBetweenMapPoints(mapPoint1, mapPoint2) return Float(distance) } func find_centroids() { if self.clustered_message_array.isEmpty == true { return } self.centroid_array = [Message]() var i = 0 while i < self.num_clusters { var cluster_stack = [Message]() for message in self.clustered_message_array { if message.cluster_id == i { cluster_stack.append(message) let object:Message = message print("Cluster Stack:", object.msg_id, object.lat, object.lon, object.tag, object.cluster_id, object.distance) } } i += 1 let lowest_point:Message = self.calculate_lowest_cost(cluster_stack) self.centroid_array.append(lowest_point) } print("Centroid Array Count:", centroid_array.count) return } func calculate_lowest_cost(cluster_stack: [Message]) -> Message { // for each cluster stack, iterate through for each point; // take sum of distances of each point against potential centroid point var work_stack = [Message]() var work_cluster = [Message]() work_stack = cluster_stack work_cluster = cluster_stack /* for point in cluster_stack { /* let object: Message = point print("Cluster_Stack Message:", object.msg_id, object.lat, object.lon, object.tag, object.cluster_id, object.distance) */ } */ var i = 0 var lowest_dist_sum:Float = 0 var potential_centroid = Message() var lowest_point = Message() while (!work_stack.isEmpty) { print("Work Stack Count:", work_stack.count) potential_centroid = work_stack.popLast()! // let object: Message = potential_centroid // print("Potential Centroid:", object.msg_id, object.lat, object.lon, object.tag, object.cluster_id, object.distance) i += 1 let lat1 = (potential_centroid.lat)! let lon1 = (potential_centroid.lon)! var dist_sum:Float = 0 for point in work_cluster { let lat2 = Float(point.lat) let lon2 = Float(point.lon) if lat1 == lat2 && lon1 == lon2 { distance = 0 } else { distance = self.calculate_distance(lat1, lon1: lon1, lat2: lat2, lon2: lon2) dist_sum += distance } } let potential_centroid_index:Int = self.findIndex(potential_centroid) self.clustered_message_array[potential_centroid_index].cost = dist_sum potential_centroid.cost = dist_sum if (lowest_dist_sum == 0 || dist_sum < lowest_dist_sum) { lowest_dist_sum = dist_sum lowest_point = potential_centroid } } return lowest_point } func findIndex(potential_centroid: Message) -> Int { var potential_centroid_index = -1 for (index, point) in EnumerateSequence(self.clustered_message_array) { potential_centroid_index = index if (potential_centroid.msg_id == point.msg_id) { print("Potential_centroid_index:", potential_centroid_index) potential_centroid_index = index } } return potential_centroid_index } func find_average(cluster_stacks: [Message]){ var total_lat:Float = 0.0 var total_lon: Float = 0.0 for cluster_stack in cluster_stacks { total_lon = cluster_stack.lon + total_lon total_lat = cluster_stack.lat + total_lat } print("Cluster Average:", total_lat/Float(cluster_stacks.count),",",total_lon/Float(cluster_stacks.count)) } }
true
812a06974af30aceb4722731a11ef95d0c58f82e
Swift
codesman/xswift
/exercises/hello-world/helloWorldExample.swift
UTF-8
118
2.96875
3
[ "MIT" ]
permissive
struct HelloWorld { static func hello(text:String = "World") -> String{ return "Hello, \(text)!" } }
true
8837b109632e294a7f6b6a216d50f9b5244443cb
Swift
AnKo4/CollectionViewTestApp
/CollectionViewTestApp/ViewController.swift
UTF-8
1,680
3.015625
3
[]
no_license
// // ViewController.swift // CollectionViewTestApp // // Created by Andrey on 09.10.2019. // Copyright © 2019 Andrey. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet private weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self collectionView.delegate = self collectionView.register(UINib(nibName: "CollectionViewCell", bundle: .main), forCellWithReuseIdentifier: "cell") } } extension ViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell cell.label.text = "\(indexPath.item)" return cell } } extension ViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { switch indexPath.item { case 0: return CGSize(width: collectionView.frame.width * 0.6, height: collectionView.frame.height) case 1,2: return CGSize(width: collectionView.frame.width * 0.4, height: collectionView.frame.height * 0.5) default: return CGSize(width: collectionView.frame.width * 0.5, height: collectionView.frame.height * 0.5) } } }
true
4283169adee55094a8d970e8484cae2464398acb
Swift
MacMeDan/upload2aws
/upload2AWS/URlSessionManager.swift
UTF-8
2,275
2.71875
3
[]
no_license
// // URlSessionManager.swift // upload2AWS // // Created by P D Leonard on 1/30/17. // Copyright © 2017 MacMeDan. All rights reserved. // import Foundation import UIKit class URlSessionManager: NSObject { static var shared = URlSessionManager() lazy var backgroundUploadSession : URLSession = { let configuration = URLSessionConfiguration.background(withIdentifier: "BackgroundThreadIdentifier") let urlSession = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) return urlSession }() var responseData = NSMutableData() var thetotalBytesSent = Int64() } extension URlSessionManager: URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate { func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { print("session \(session), received response \(response)") completionHandler(Foundation.URLSession.ResponseDisposition.allow) } func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { thetotalBytesSent = thetotalBytesSent + totalBytesExpectedToSend } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { responseData.append(data) } func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { if let appDelegate = UIApplication.shared.delegate as? AppDelegate { if let completionHandler = appDelegate.backgroundSessionCompletionHandler { appDelegate.backgroundSessionCompletionHandler = nil DispatchQueue.main.async (execute: { completionHandler() }) } } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if error != nil { print("\n ERROR: session: \(session),for task: \(task), \n\n Error Description: \(error?.localizedDescription)") } else { print("Completed task:\(task.taskIdentifier)") } } }
true
9e1dd7442eba8281e4a69ff25613f60bd11182fb
Swift
BACTERIAFISH/Tastopia
/Tastopia/Model/Firebase/FirestoreManager.swift
UTF-8
6,034
2.703125
3
[]
no_license
// // FirestoreManager.swift // Tastopia // // Created by FISH on 2020/2/1. // Copyright © 2020 FISH. All rights reserved. // import Firebase import FirebaseFirestoreSwift class FirestoreManager { enum FirestoreManagerError: Error { case fetchError(String) } let db = Firestore.firestore() let storage = Storage.storage() let storageRef: StorageReference! init() { storageRef = storage.reference() } func addData(docRef: DocumentReference, data: [String: Any]) { docRef.setData(data, merge: true) } func addCustomData<T: Codable>(docRef: DocumentReference, data: T) { do { try docRef.setData(from: data, merge: true) } catch { print("Firestore setData error: \(error)") } } func readData(_ ref: DocumentReference, completion: @escaping (Result<DocumentSnapshot?, Error>) -> Void) { ref.getDocument { (snapshot, error) in if let error = error { completion(Result.failure(FirestoreManagerError.fetchError(error.localizedDescription))) return } completion(Result.success(snapshot)) } } func readData(_ ref: CollectionReference, completion: @escaping (Result<QuerySnapshot?, Error>) -> Void) { ref.getDocuments { (snapshot, error) in if let error = error { completion(Result.failure(FirestoreManagerError.fetchError(error.localizedDescription))) return } completion(Result.success(snapshot)) } } func readData(_ ref: Query, completion: @escaping (Result<QuerySnapshot?, Error>) -> Void) { ref.getDocuments { (snapshot, error) in if let error = error { completion(Result.failure(FirestoreManagerError.fetchError(error.localizedDescription))) return } completion(Result.success(snapshot)) } } func readCustomData<T: Codable>(collection: String, document: String, dataType: T.Type, completion: @escaping (Result<T, Error>) -> Void) { let docRef = db.collection(collection).document(document) docRef.getDocument { (doc, error) in if let error = error { completion(Result.failure(error)) return } let result = Result { try doc.flatMap { try $0.data(as: T.self) } } switch result { case .success(let data): if let data = data { completion(Result.success(data)) } else { print("Document does not exist.") } case .failure(let error): completion(Result.failure(error)) } } } func updateArrayData<T: Codable>(collection: String, document: String, field: String, data: [T], completion: ((Error?) -> Void)? = { _ in }) { db.collection(collection).document(document).updateData([ field: FieldValue.arrayUnion(data) ]) { error in completion?(error) } } func incrementData(collection: String, document: String, field: String, increment: Int64) { db.collection(collection).document(document).updateData([ field: FieldValue.increment(increment) ]) } func deleteArrayData<T: Codable>(collection: String, document: String, field: String, data: [T]) { db.collection(collection).document(document).updateData([ field: FieldValue.arrayRemove(data) ]) } func uploadImage(image: UIImage, fileName: String?, completion: @escaping (Result<String, Error>) -> Void) { let uuid = NSUUID().uuidString var path = "images/\(uuid).JPEG" if let fileName = fileName { path = "users/\(fileName).JPEG" } let imageRef = storageRef.child(path) guard let data = image.jpegData(compressionQuality: 0.5) else { return } let uploadTask = imageRef.putData(data, metadata: nil) { (_, error) in if let error = error { completion(Result.failure(error)) } // guard let metadata = metadata else { return } imageRef.downloadURL { (url, error) in if let error = error { completion(Result.failure(error)) } guard let downloadURL = url else { return } completion(Result.success(downloadURL.absoluteString)) } } uploadTask.resume() } func uploadVideo(url: URL, completion: @escaping (Result<String, Error>) -> Void) { let uuid = NSUUID().uuidString let path = "video/\(uuid).MOV" let videoRef = storageRef.child(path) do { let data = try Data(contentsOf: url) let uploadTask = videoRef.putData(data, metadata: nil) { (_, error) in if let error = error { completion(Result.failure(error)) } // guard let metadata = metadata else { return } videoRef.downloadURL { (videoURL, error) in if let error = error { completion(Result.failure(error)) } guard let downloadURL = videoURL else { return } completion(Result.success(downloadURL.absoluteString)) } } uploadTask.resume() } catch { print(error) } } }
true
dc79ae731a520e279d44115cfc5586b8b2dc7355
Swift
radude89/uniter
/ios-app/Uniter/ContentView.swift
UTF-8
3,211
2.90625
3
[ "MIT" ]
permissive
// // ContentView.swift // Uniter // // Created by Radu Dan on 11/08/2020. // import SwiftUI import WidgetKit struct ContentView: View { @ObservedObject var dataLoader = DataLoader() @State private var showingWidgetMeetup = false @State private var selectedMeetup: Meetup? var body: some View { NavigationView { List(dataLoader.meetups) { meetup in NavigationLink( destination: MeetupView(meetup: meetup, dataLoader: dataLoader)) { Image(meetup.imageName) .resizable() .aspectRatio(contentMode: .fill) .frame(width: 80, height: 80, alignment: .center) .clipShape(Circle()) .overlay( Circle().stroke(Color.blue, lineWidth: 3) .shadow(radius: 10) ) VStack(alignment: .leading) { Text(meetup.name) .font(.headline) Text(meetup.description) } } } .navigationBarTitle("Uniter", displayMode: .inline) .onAppear(perform: fetchData) .onOpenURL(perform: openURL) .sheet(isPresented: $showingWidgetMeetup) { if let selectedMeetup = selectedMeetup { MeetupView(meetup: selectedMeetup, dataLoader: dataLoader) } } } } private func fetchData() { WidgetCenter.shared.reloadAllTimelines() fetchMeetups() fetchParticipants() } private func fetchMeetups() { dataLoader.fetch(api: "meetups") { (result: Result<[Meetup], LocalError>) in DispatchQueue.main.async { switch result { case .success(let meetups): self.dataLoader.meetups = meetups.sorted { $0.name > $1.name } case .failure(.generic(let errorMessage)): print(errorMessage) } } } } private func fetchParticipants() { dataLoader.fetch(api: "participants") { (result: Result<[Participant], LocalError>) in DispatchQueue.main.async { switch result { case .success(let participants): self.dataLoader.participants = participants case .failure(.generic(let errorMessage)): print(errorMessage) } } } } private func openURL(_ url: URL) { guard let uuid = UUID(uuidString: url.lastPathComponent) else { return } guard let meetup = dataLoader.meetups.first(where: { $0.id == uuid }) else { return } // buggy selectedMeetup = meetup showingWidgetMeetup = true } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
true
2a05f5a3454ccb24db3cbf377c9db386aa941261
Swift
krzysztofkogut/Soundizer
/Soundizer/ViewModels/InstrumentListViewModel.swift
UTF-8
1,091
2.65625
3
[]
no_license
// // InstrumentListViewModel.swift // Soundizer // // Created by Krzysztof Kogut on 16/12/2020. // import Foundation import Combine class InstrumentListViewModel: ObservableObject { @Published var instrumentRepository = InstrumentRepository() @Published var instrumentCellViewModels = [InstrumentCellViewModel]() private var cancellables = Set<AnyCancellable>() init() { instrumentRepository.$instruments.map { instruments in instruments.map { instrument in InstrumentCellViewModel(instrument: instrument) } } .assign(to: \.instrumentCellViewModels, on: self) .store(in: &cancellables) } func removeInstrument(atOffsets index: IndexSet) { let viewModels = index.lazy.map { self.instrumentCellViewModels[$0] } viewModels.forEach { instrumentCellViewModel in instrumentRepository.removeInstrument(instrumentCellViewModel.instrument) } } func addInstrument(instrument: Instrument) { instrumentRepository.addInstrument(instrument) } }
true
15582aeabb5b8ccbe7794cc624d2f083fe7611a8
Swift
GeneralD/CollectionKit
/Sources/CollectionKit/Sequence+Sorting.swift
UTF-8
687
3.46875
3
[ "BSD-3-Clause", "BSD-2-Clause-Views" ]
permissive
// // Sequence+Sorting.swift // // // Created by Yumenosuke Koukata on 2020/10/22. // import Foundation public extension Sequence { func sorted<Where>(at: (Element) throws -> Where, by: (Where, Where) throws -> Bool) rethrows -> [Element] { try sorted { try by(at($0), at($1)) } } func ascended<Where: Comparable>(at: (Element) throws -> Where) rethrows -> [Element] { try sorted(at: at, by: <) } func descended<Where: Comparable>(at: (Element) throws -> Where) rethrows -> [Element] { try sorted(at: at, by: >) } } public extension Sequence where Element: Comparable { var ascended: [Element] { sorted(by: <) } var descended: [Element] { sorted(by: >) } }
true
51742a3659c4c1a4b89a248117b3909f6e75db0f
Swift
nikita-leonov/boss-client
/BoSS/Services/CategoriesService.swift
UTF-8
1,126
3.03125
3
[ "MIT" ]
permissive
// // CategoriesService.swift // BoSS // // Created by Emanuele Rudel on 28/02/15. // Copyright (c) 2015 Bureau of Street Services. All rights reserved. // import Foundation private let categoriesDictionary: [String: String] = [ "POTHOLE" : "Pothole", "DEBRIS" : "Debris on Road", "DAMAGED_SIDEWALK" : "Damaged Sidewalk", "STREET_SWEEPING" : "Street Cleaning", "BROKEN_STREETLIGHTS" : "Broken Streetlight", ] class CategoriesService: CategoriesServiceProtocol { internal class func category(forIdentifier identifier: String) -> Category? { var result: Category? if let name = categoriesDictionary[identifier] { result = Category(name: name, identifier: identifier) } return result } private lazy var fixedCategories: [Category] = { var result = [Category]() for (id, name) in categoriesDictionary { result.append(Category(name: name, identifier: id)) } return result }() func categories() -> [Category] { return fixedCategories } }
true
6a829884b6cb96f04109f8fbb2fcba27ce595662
Swift
joaoduartemariucio/estudos-ios
/MVVM with RxSwift/MVVM with RxSwift/Login/Model/UserCredential.swift
UTF-8
370
2.640625
3
[]
no_license
// // UserCredential.swift // MVVM with RxSwift // // Created by Osama Bin Bashir on 16/12/2018. // Copyright © 2018 Osama Bin Bashir. All rights reserved. // import Foundation struct UserCredential { let userName : String let password : String init(userName : String, password : String) { self.userName = userName self.password = password } }
true
09b56688046c99f8845228d8bf25e27b2f247fcf
Swift
roger-tan/Whitbread-Challenge
/Whitbread-Challenge/Models/VenueChains.swift
UTF-8
1,813
3.0625
3
[]
no_license
// // VenueChains.swift // // Created by Roger TAN on 8/10/16 // Copyright (c) Roger TAN. All rights reserved. // import Foundation import SwiftyJSON public class VenueChains: NSObject, NSCoding { // MARK: Declaration for string constants to be used to decode and also serialize. internal let kVenueChainsInternalIdentifierKey: String = "id" // MARK: Properties public var internalIdentifier: String? // MARK: SwiftyJSON Initalizers /** Initates the class based on the object - parameter object: The object of either Dictionary or Array kind that was passed. - returns: An initalized instance of the class. */ convenience public init(object: AnyObject) { self.init(json: JSON(object)) } /** Initates the class based on the JSON that was passed. - parameter json: JSON object from SwiftyJSON. - returns: An initalized instance of the class. */ public init(json: JSON) { internalIdentifier = json[kVenueChainsInternalIdentifierKey].string } /** Generates description of the object in the form of a NSDictionary. - returns: A Key value pair containing all valid values in the object. */ public func dictionaryRepresentation() -> [String : AnyObject ] { var dictionary: [String : AnyObject ] = [ : ] if internalIdentifier != nil { dictionary.updateValue(internalIdentifier!, forKey: kVenueChainsInternalIdentifierKey) } return dictionary } // MARK: NSCoding Protocol required public init(coder aDecoder: NSCoder) { self.internalIdentifier = aDecoder.decodeObjectForKey(kVenueChainsInternalIdentifierKey) as? String } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(internalIdentifier, forKey: kVenueChainsInternalIdentifierKey) } }
true
a10052954def3ecd15078912cb7e2b7a7a9a4f77
Swift
emilyannemoses/iOS-Development
/swift_tutorials/dictionaries-practice.swift
UTF-8
1,288
4.125
4
[]
no_license
// Dictionaries vs. arrays var todo = [1, 2, 3, 4, 5, 6] todo[0] todo[5] /* Airport Code {key} Airport Name {value} LGA La Guardia LHR Heathrow CDG Charles de Gaulle HKG Hong Kong International DXB Dubai International */ // Key Value Pair // Dictionaries DO NOT preserve order. var airportCodes: [String:String] = [ "LGA": "La Guardia", "LHR": "Heathrow", "CDG": "Charles de Gaulle", "HKG": "Hong Kong International", "DXB": "Dubai International" ] let currentWeather: [String:Double] = ["temperature": 75.0] // Get airportCodes["LGA"] // Assign airportCodes["SYD"] = "Sydney Airport" // Updating existing key value airportCodes["LGA"] = "La Guardia International Airport" airportCodes.updateValue("Dublin Airport", forKey: "CDG") // Removal airportCodes.removeValue(forKey: "CDG") // Dealing with non existent data // Optional can contain one of two values. If it doesn't contain one it'll return nil let newYorkAirport = airportCodes["LGA"] type(of: newYorkAirport) // Example of Optional type let orlandoAirport = airportCodes["MCL"] // Doesn't exist, so this optional value returns nil.
true
486024fe21464b3f7d576ec5a3bceca7a963aa0c
Swift
c2ktqxgo/tuist
/Sources/TuistCoreTesting/Utils/MockPrinter.swift
UTF-8
2,732
2.546875
3
[ "MIT" ]
permissive
import Basic import Foundation import TuistCore import XCTest public final class MockPrinter: Printing { var standardOutput: String = "" var standardError: String = "" public func print(_ text: String) { standardOutput.append("\(text)\n") } public func print(section: String) { standardOutput.append("\(section)\n") } public func print(warning: String) { standardOutput.append("\(warning)\n") } public func print(deprecation: String) { standardOutput.append("\(deprecation)\n") } public func print(errorMessage: String) { standardError.append("\(errorMessage)\n") } public func print(error: Error) { standardError.append("\(error.localizedDescription)\n") } public func print(success: String) { standardOutput.append("\(success)\n") } public func print(subsection: String) { standardOutput.append("\(subsection)\n") } func standardOutputMatches(with pattern: String) -> Bool { return standardOutput.contains(pattern) } func standardErrorMatches(with pattern: String) -> Bool { return standardError.contains(pattern) } } extension XCTestCase { func XCTAssertPrinterOutputContains(_ expected: String, file: StaticString = #file, line: UInt = #line) { guard let printer = sharedMockPrinter(file: file, line: line) else { return } let message = """ The standard output: =========== \(printer.standardOutput) Doesn't contain the expected output: =========== \(expected) """ XCTAssertTrue(printer.standardOutputMatches(with: expected), message, file: file, line: line) } func XCTAssertPrinterErrorContains(_ expected: String, file: StaticString = #file, line: UInt = #line) { guard let printer = sharedMockPrinter(file: file, line: line) else { return } let message = """ The standard error: =========== \(printer.standardError) Doesn't contain the expected output: =========== \(expected) """ XCTAssertTrue(printer.standardErrorMatches(with: expected), message, file: file, line: line) } fileprivate func sharedMockPrinter(file: StaticString = #file, line: UInt = #line) -> MockPrinter? { guard let mock = Printer.shared as? MockPrinter else { let message = "Printer.shared hasn't been mocked." + "You can call mockPrinter(), or mockSharedInstances() to mock the printer or the environment respectively." XCTFail(message, file: file, line: line) return nil } return mock } }
true
39a7ced380ac4d3f0bab100b99813a527901fc93
Swift
GrinevichSergey/puotb
/Calendar/controller/CalendarViewController.swift
UTF-8
5,508
2.53125
3
[]
no_license
// // CalendarViewController.swift // basic_xcode // // Created by Сергей Гриневич on 23/08/2019. // Copyright © 2019 Green. All rights reserved. // import UIKit import JTAppleCalendar class CalendarViewController: UIViewController, UIPickerViewDataSource,UIPickerViewDelegate { @IBOutlet weak var calendar: JTAppleCalendarView! @IBOutlet weak var smenaPicker: UIPickerView! let smenaField = ["1 смена", "2 смена", "3 смена", "4 смена"] override func viewDidLoad() { super.viewDidLoad() calendar.scrollDirection = .horizontal calendar.scrollingMode = .stopAtEachCalendarFrame calendar.showsHorizontalScrollIndicator = false calendar.allowsMultipleSelection = true calendar.isRangeSelectionUsed = true self.smenaPicker.dataSource = self self.smenaPicker.delegate = self } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { smenaField.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { smenaField[row] } func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { return NSAttributedString(string: smenaField[row], attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]) } func confugureCell(view: JTAppleCell?, cellState: CellState){ guard let cell = view as? DateCell else { return } cell.dateLabel.text = cellState.text handleCellTextColor(cell: cell, cellState: cellState) handleCellSelected(cell: cell, cellState: cellState) } func handleCellTextColor(cell: DateCell, cellState: CellState) { if cellState.dateBelongsTo == .thisMonth { cell.dateLabel.textColor = UIColor.black cell.selectedView.backgroundColor = .red } else { cell.dateLabel.textColor = UIColor.gray } } func handleCellSelected(cell: DateCell, cellState: CellState) { cell.selectedView.isHidden = !cellState.isSelected switch cellState.selectedPosition() { case .left: cell.selectedView.layer.cornerRadius = 20 cell.selectedView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMinXMinYCorner] case .middle: cell.selectedView.layer.cornerRadius = 0 cell.selectedView.layer.maskedCorners = [] case .right: cell.selectedView.layer.cornerRadius = 20 cell.selectedView.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner] case .full: cell.selectedView.layer.cornerRadius = 20 cell.selectedView.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMinXMinYCorner] default: break } } } extension CalendarViewController: JTAppleCalendarViewDataSource { func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters { let formatter = DateFormatter() formatter.dateFormat = "yyyy MM dd" let startDate = formatter.date(from: "2019 08 01")! let endDate = Date() return ConfigurationParameters(startDate: startDate, endDate: endDate, generateInDates: .forAllMonths, generateOutDates: .tillEndOfGrid) } } extension CalendarViewController: JTAppleCalendarViewDelegate { func calendar(_ calendar: JTAppleCalendarView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTAppleCell { let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "dateCell", for: indexPath) as! DateCell self.calendar(calendar, willDisplay: cell, forItemAt: date, cellState: cellState, indexPath: indexPath) return cell } func calendar(_ calendar: JTAppleCalendarView, willDisplay cell: JTAppleCell, forItemAt date: Date, cellState: CellState, indexPath: IndexPath) { confugureCell(view: cell, cellState: cellState) } func calendar(_ calendar: JTAppleCalendarView, headerViewForDateRange range: (start: Date, end: Date), at indexPath: IndexPath) -> JTAppleCollectionReusableView { let formatter = DateFormatter() // Declare this outside, to avoid instancing this heavy class multiple times. formatter.dateFormat = "MMM" let header = calendar.dequeueReusableJTAppleSupplementaryView(withReuseIdentifier: "DateHeader", for: indexPath) as! DateHeader header.monthTitle.text = formatter.string(from: range.start) return header } func calendarSizeForMonths(_ calendar: JTAppleCalendarView?) -> MonthSize? { return MonthSize(defaultSize: 50) } func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleCell?, cellState: CellState) { confugureCell(view: cell, cellState: cellState) } func calendar(_ calendar: JTAppleCalendarView, didDeselectDate date: Date, cell: JTAppleCell?, cellState: CellState) { confugureCell(view: cell, cellState: cellState) } }
true
52f8ee4ce062a824c97f937d4a0e2857287483cb
Swift
kazakovaNetIOS/Notepad
/Notepad/Controllers/AddNoteViewController.swift
UTF-8
1,080
2.921875
3
[]
no_license
// // AddNoteViewController.swift // Notepad // // Created by Natalia Kazakova on 08/06/2019. // Copyright © 2019 Natalia Kazakova. All rights reserved. // import UIKit class AddNoteViewController: UIViewController { @IBOutlet weak var titleTextField: UITextField! @IBOutlet weak var textTextView: UITextView! let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext override func viewDidLoad() { super.viewDidLoad() } @IBAction func saveButtonPressed(_ sender: UIButton) { let newNote = NoteItem(context: context) newNote.title = titleTextField.text newNote.text = textTextView.text self.saveNotes() navigationController?.popToRootViewController(animated: true) } // MARK: - Data manipulation methods func saveNotes() { do { try context.save() } catch { print("Error saving notes in context \(error)") } dismiss(animated: true, completion: nil) } }
true
e1ad0ef50f64878ffcab9558d3ec6b450d2ac544
Swift
AhmedOS/Shield
/Shield/View Controllers/PasswordBreach/PasswordBreachVC.swift
UTF-8
2,020
2.71875
3
[]
no_license
// // PasswordBreachVC.swift // Shield // // Created by Ahmed Osama on 12/17/18. // Copyright © 2018 Ahmed Osama. All rights reserved. // import UIKit class PasswordBreachVC: UIViewController { @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var checkButton: UIButton! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() passwordTextField.delegate = self } @IBAction func checkButtonTapped(_ sender: Any) { guard passwordTextField.text != "" else { Helpers.showSimpleAlert(viewController: self, title: "Error", message: "Empty password") return } enableUIControls(false) PwnedClient.requestPasswordBreach(passwordTextField.text!) { (seenCount, errorMessage) in self.enableUIControls(true) guard let count = seenCount else { Helpers.showSimpleAlert(viewController: self, title: "Error", message: errorMessage!) return } if count == 0 { Helpers.showSimpleAlert(viewController: self, title: "Good news!", message: "We didn't find the password in our database. Note that doesn't necessarily mean it's a good password.") } else { Helpers.showSimpleAlert(viewController: self, title: "Uh oh!!", message: "This password has been seen \(count) time\(count == 1 ? "" : "s").") } } } func enableUIControls(_ enabled: Bool) { DispatchQueue.main.async { self.passwordTextField.isEnabled = enabled self.checkButton.isEnabled = enabled enabled ? self.activityIndicator.stopAnimating() : self.activityIndicator.startAnimating() } } } extension PasswordBreachVC: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true; } }
true
e8657390db727e404bdf56aba958c9aaee5986e1
Swift
DenRayzer/Distillery_HW2
/Palindrome.swift
UTF-8
489
3.34375
3
[]
no_license
import UIKit func isPalindrome(s : inout String){ var arr = s.split(separator: " ") var s1:String = "" for i in 0..<arr.count { s1 += arr[i] if String(s1.reversed())==s1{ print(s1) } } if(arr.count>1) { let endRemoveIndex = s.index(s.startIndex, offsetBy: arr[0].count) s.removeSubrange(s.startIndex...endRemoveIndex) isPalindrome(s: &s) } } var s = "tar rat mam mam tar rat" isPalindrome(s: &s)
true
a5a3940fa9205b0ec94a59fac43fcfc24b9e9abf
Swift
LiamDuffyer/ExpenditureTracker
/NoticeDetail/NoticeAttachmentCell.swift
UTF-8
4,684
2.578125
3
[]
no_license
// // NoticeAttachmentCell.swift // import UIKit import Alamofire protocol AttachmentDelegate : class { func showDocumentInteractionController(filePath: String) func showIndicator() } class NoticeAttachmentCell: UITableViewCell { @IBOutlet var attachmentTitle: UILabel! @IBOutlet var btnDownload: UIButton! weak var cellDelegate : AttachmentDelegate? var majorCode: DeptCode? var fileName = String() var fileDownloadURL = String() var viewController: BaseViewController? @IBAction func onClickDownload(_ sender: Any) { showAlert(title: "파일 다운로드", msg: "파일을 다운로드하시겠습니까?", handler: doDownloadFile(_:)) } func doDownloadFile(_ action: UIAlertAction) { var encodedUrl = self.fileDownloadURL if majorCode ?? DeptCode.IT_Computer == DeptCode.LAW_IntlLaw || majorCode ?? DeptCode.IT_Computer == DeptCode.Inmun_Korean || majorCode ?? DeptCode.IT_Computer == DeptCode.Inmun_French || majorCode ?? DeptCode.IT_Computer == DeptCode.Inmun_Chinese || majorCode ?? DeptCode.IT_Computer == DeptCode.Inmun_English || majorCode ?? DeptCode.IT_Computer == DeptCode.Inmun_History || majorCode ?? DeptCode.IT_Computer == DeptCode.Inmun_Philosophy || majorCode ?? DeptCode.IT_Computer == DeptCode.Inmun_Japanese || majorCode ?? DeptCode.IT_Computer == DeptCode.Engineering_Machine || majorCode ?? DeptCode.IT_Computer == DeptCode.Engineering_Industrial || majorCode ?? DeptCode.IT_Computer == DeptCode.NaturalScience_Math || majorCode ?? DeptCode.IT_Computer == DeptCode.NaturalScience_Physics || majorCode ?? DeptCode.IT_Computer == DeptCode.NaturalScience_Chemistry || majorCode ?? DeptCode.IT_Computer == DeptCode.NaturalScience_Medical || majorCode ?? DeptCode.IT_Computer == DeptCode.Business_biz || majorCode ?? DeptCode.IT_Computer == DeptCode.Business_venture || majorCode ?? DeptCode.IT_Computer == DeptCode.Business_Account || majorCode ?? DeptCode.IT_Computer == DeptCode.Business_Finance || majorCode ?? DeptCode.IT_Computer == DeptCode.Economy_Economics || majorCode ?? DeptCode.IT_Computer == DeptCode.Economy_GlobalCommerce || majorCode ?? DeptCode.IT_Computer == DeptCode.Social_Welfare || majorCode ?? DeptCode.IT_Computer == DeptCode.Social_Administration || majorCode ?? DeptCode.IT_Computer == DeptCode.Social_Sociology || majorCode ?? DeptCode.IT_Computer == DeptCode.Social_Journalism || majorCode ?? DeptCode.IT_Computer == DeptCode.Social_LifeLong || majorCode ?? DeptCode.IT_Computer == DeptCode.Social_Political || majorCode ?? DeptCode.IT_Computer == DeptCode.MIX_mix { encodedUrl = self.fileDownloadURL } else { encodedUrl = self.fileDownloadURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "" } print("download : \(encodedUrl)") self.cellDelegate?.showIndicator() let destination: DownloadRequest.DownloadFileDestination = { _, _ in let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let fileURL = documentsURL.appendingPathComponent(self.fileName) return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) } Alamofire.download(encodedUrl ?? "", to: destination) .downloadProgress { progress in print("Download Progress: \(progress.fractionCompleted)") } .response { response in debugPrint(response) if let filePath = response.destinationURL?.path { print("Downloaded File Path : " + filePath) self.cellDelegate?.showDocumentInteractionController(filePath: filePath) } } print("B") } func showAlert(title: String, msg: String, handler: ((UIAlertAction) -> Swift.Void)?){ let alertController = UIAlertController(title: title, message: msg, preferredStyle: .alert) let yesButton = UIAlertAction(title: "예", style: .default, handler: handler) alertController.addAction(yesButton) let noButton = UIAlertAction(title: "아니요", style:.destructive, handler: nil) alertController.addAction(noButton) viewController?.present(alertController, animated: true, completion: nil) } }
true
dd0c37315272e13f63b8b3af3663f77278c56a4a
Swift
kangraemin/IOS-Study
/BMI-Calculator-iOS13/BMI Calculator/CalculatorBrain.swift
UTF-8
706
3.109375
3
[]
no_license
// // CalculatorBrain.swift // BMI Calculator // // Created by 강래민 on 2020/11/22. // Copyright © 2020 Angela Yu. All rights reserved. // import Foundation struct CalculatorBrain { var bmi: Float? mutating func calculateBMI(weight: Float, height: Float) { bmi = weight / (height * height) } func getBMIValue() -> String { // if bmi != nil { // return String(format: "%.1f", bmi!) // } else { // return "0.0" // } // if let safeBMI = bmi { // return String(format: "%.1f", safeBMI) // } else { // return "0.0" // } return String(format: "%.1f", bmi ?? 0.0) } }
true
bc79561481533b756bb2d038687adfde684e3046
Swift
surgiollc/NetworkingController
/NetworkingController/Sources/JSONAPI/JSONDocument.swift
UTF-8
2,563
2.6875
3
[ "MIT" ]
permissive
// // JSONDocument.swift // NetworkingController // // Created by Chandler De Angelis on 4/6/18. // Copyright © 2018 Chandler De Angelis. All rights reserved. // import Foundation public struct JSONDocument: JSONAPIResource { public var json: JSONObject public var rootDataObject: JSONObject? { return self.json["data"] as? JSONObject } public var data: Data? { return try? JSONSerialization.data(withJSONObject: self.json, options: []) } init(json: JSONObject) { self.json = json } public init(resource: JSONResource) { self.json = ["data": resource.json] } public init(resources: [JSONResource]) { self.json = [ "data": resources.map({ $0.json }) ] } public init?(data: Data) { if let object: Any = try? JSONSerialization.jsonObject(with: data, options: []), let json: JSONObject = object as? JSONObject, // either "data" or "errors", or "meta" must be present for this to be a valid JSONDocument (json["data"] != nil || json["errors"] != nil) || json["meta"] != nil { self.json = json } else { return nil } } public var resourceObjects: [JSONResource]? { get { guard case let objects as [JSONObject] = self["data"] else { return .none } return objects.map(JSONResource.init) } set { self["data"] = newValue?.map({ $0.json }) } } public var resourceObject: JSONResource? { get { guard case let object as JSONObject = self["data"] else { return .none } return JSONResource(json: object) } set { self["data"] = newValue?.json } } public mutating func remove(_ resource: JSONResource) { guard let index: Int = self.resourceObjects?.index(of: resource) else { return } self.resourceObjects?.remove(at: index) } public var links: JSONObject? { return self["links"] as? JSONObject } public var meta: JSONObject? { return self["meta"] as? JSONObject } public var errors: [JSONObject] { return self["errors"] as? [JSONObject] ?? [] } public var includes: [JSONResource] { guard let included = self["included"] as? [JSONObject] else { return [] } return included.map(JSONResource.init) } }
true
b0916b4426c6054483cac11eaacbada41e91fd1e
Swift
ugozeal/Fund_All_Challenge
/FundAll_App/Utilities/Extensions/String+Extension.swift
UTF-8
281
2.546875
3
[]
no_license
// // String+Extension.swift // FundAll_App // // Created by David U. Okonkwo on 2/17/21. // import Foundation extension String { var isValidEmail: Bool { NSPredicate(format: "SELF MATCHES %@", "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}").evaluate(with: self) } }
true
946d82483e81d79b714d7cb8f53c56fb882b1ac7
Swift
clyksb0731/Summaries_Practices
/TableViewSummary/TableViewSummary/TableViewCell.swift
UTF-8
4,251
2.671875
3
[]
no_license
// // TableViewCell.swift // TableViewSummary // // Created by 최용석 on 29/10/2018. // Copyright © 2018 최용석. All rights reserved. // import UIKit class TableViewCell: UITableViewCell { var sequence: UILabel! var viewControllerName: UILabel! var safeGuide: UILayoutGuide! var marginGuide: UILayoutGuide! override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.safeGuide = self.contentView.safeAreaLayoutGuide self.marginGuide = self.contentView.layoutMarginsGuide self.createObjects() self.setAnchor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func createObjects() { // For sequnces of view controllers self.sequence = UILabel() self.sequence.textColor = .black self.sequence.textAlignment = .center self.sequence.font = UIFont.systemFont(ofSize: 20) // self.sequence.layer.borderColor = UIColor.black.cgColor // self.sequence.layer.borderWidth = 1 self.sequence.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(self.sequence) // For viewController's name self.viewControllerName = UILabel() self.viewControllerName.textColor = .black self.viewControllerName.textAlignment = .center self.viewControllerName.font = UIFont.systemFont(ofSize: 20) // self.viewControllerName.layer.borderColor = UIColor.black.cgColor // self.viewControllerName.layer.borderWidth = 1 self.viewControllerName.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(self.viewControllerName) } func setAnchor() { // Layout of view controllers' sequence self.sequence.widthAnchor.constraint(equalTo: self.marginGuide.widthAnchor, multiplier: 0.2).isActive = true self.sequence.leadingAnchor.constraint(equalTo: self.marginGuide.leadingAnchor).isActive = true self.sequence.topAnchor.constraint(equalTo: self.marginGuide.topAnchor).isActive = true self.sequence.bottomAnchor.constraint(equalTo: self.marginGuide.bottomAnchor).isActive = true // Layout of view controllers' name self.viewControllerName.widthAnchor.constraint(equalTo: self.marginGuide.widthAnchor, multiplier: 0.8).isActive = true self.viewControllerName.trailingAnchor.constraint(equalTo: self.marginGuide.trailingAnchor).isActive = true self.viewControllerName.topAnchor.constraint(equalTo: self.marginGuide.topAnchor).isActive = true self.viewControllerName.bottomAnchor.constraint(equalTo: self.marginGuide.bottomAnchor).isActive = true /// Safe Area to test // Layout of view controllers' sequence // self.sequence.widthAnchor.constraint(equalTo: self.safeGuide.widthAnchor, multiplier: 0.2).isActive = true // self.sequence.leadingAnchor.constraint(equalTo: self.safeGuide.leadingAnchor).isActive = true // self.sequence.topAnchor.constraint(equalTo: self.safeGuide.topAnchor).isActive = true // self.sequence.bottomAnchor.constraint(equalTo: self.marginGuide.bottomAnchor).isActive = true // // Layout of view controllers' name // self.viewControllerName.widthAnchor.constraint(equalTo: self.safeGuide.widthAnchor, multiplier: 0.5).isActive = true // self.viewControllerName.trailingAnchor.constraint(equalTo: self.safeGuide.trailingAnchor).isActive = true // self.viewControllerName.topAnchor.constraint(equalTo: self.safeGuide.topAnchor).isActive = true // self.viewControllerName.bottomAnchor.constraint(equalTo: self.safeGuide.bottomAnchor).isActive = true } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
true
ae344f837eafaa66795e2d4304a84a33d399fabb
Swift
dmaulikr/Whack-A-Mole
/Whack-A-Mole/Whack-A-Mole/Tile.swift
UTF-8
667
2.796875
3
[]
no_license
// // Title.swift // Whack-A-Mole // // Created by ling on 11/3/15. // Copyright © 2015 Ling. All rights reserved. // import Foundation import UIKit class Tile{ var tileImage: UIImage var ID: Int var roleIfMole: Bool var roleName:String var soundFileName: String var soundType: String init(tileImage: UIImage, ID: Int, roleIfMole: Bool, roleName:String, soundFileName: String, soundType: String){ self.tileImage = tileImage self.ID = ID self.roleIfMole = roleIfMole self.roleName = roleName self.soundFileName = soundFileName self.soundType = soundType } }
true
d5e95b35e96e6921c56563db162cbbd4760b27d7
Swift
arifsetyoaji/InvestRight
/mc3-investor-app/Controller/LessonViewController.swift
UTF-8
6,726
2.53125
3
[]
no_license
// // LessonViewController.swift // mc3-investor-app // // Created by Muhammad Arif Setyo Aji on 15/07/20. // Copyright © 2020 Jeffry Steward W. All rights reserved. // import UIKit class LessonViewController: UIViewController { @IBOutlet weak var lessonScrollView: UIScrollView! @IBOutlet weak var lessonPageControl: UIPageControl! @IBOutlet weak var startChallengButton: UIButton! var scrollHeight: CGFloat! = 0.0 var scrollWidth: CGFloat! = 0.0 var lesson: Lesson? var indexPage = 0 override func viewDidLoad() { super.viewDidLoad() self.view.layoutIfNeeded() navigationController?.isNavigationBarHidden = false if let lesson = lesson { navigationItem.title = lesson.name } setupLessonSlider() startChallengButton.layer.cornerRadius = 10.0 startChallengButton.setTitle("Continue", for: .normal) setIndicatorForCurrentPage() } override func viewDidLayoutSubviews() { scrollWidth = lessonScrollView.frame.size.width scrollHeight = lessonScrollView.frame.size.height } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? ChallengeViewController { if let lesson = lesson { destination.challengeImage = UIImage(named: "1-lesson") destination.challengeTitle = lesson.name destination.currentLesson = lesson } } } @IBAction func pageChanged(_ sender: Any) { lessonScrollView.scrollRectToVisible(CGRect(x: scrollWidth * CGFloat(lessonPageControl.currentPage), y: 0, width: scrollWidth, height: scrollHeight), animated: true) } @IBAction func startChallenge(_ sender: UIButton) { if startChallengButton.title(for: .normal) == "Start Challenge" { performSegue(withIdentifier: "GoToChallengeSegue", sender: nil) } } @IBAction func continueTapped(_ sender: UIButton) { if let lesson = lesson { setIndicatorForCurrentPage() if indexPage >= lesson.desc1.count { indexPage = 0 //Repeat to first slide scrollToPage(page: 0, animated: true) } else { scrollToPage(page: indexPage+1, animated: true) lessonPageControl.currentPage = indexPage+1 indexPage += 1 } } } func setupPage(){ let page = (lessonScrollView.contentOffset.x)/scrollWidth lessonPageControl.currentPage = Int(page) indexPage = Int(page) } } extension LessonViewController: UIScrollViewDelegate { func setupLessonSlider() { setupPage() self.lessonScrollView.delegate = self lessonScrollView.isPagingEnabled = true lessonScrollView.showsHorizontalScrollIndicator = false lessonScrollView.showsVerticalScrollIndicator = false var frame = CGRect(x: 0, y: 0, width: 0, height: 0) if let lesson = lesson { for index in 0..<lesson.desc1.count { frame.origin.x = scrollWidth * CGFloat(index) frame.size = CGSize(width: scrollWidth, height: scrollHeight) let slide = UIView(frame: frame) let slideImage = UIImageView.init(image: UIImage(named: lesson.image!)) slideImage.frame = CGRect(x: 32, y: 37, width: 55, height: 55) slideImage.contentMode = .scaleAspectFit //slideImage.center = CGPoint(x: scrollWidth/2, y: scrollHeight/2 - 15) let slideTitle = UILabel.init(frame: CGRect(x: 95, y: 37, width: 120, height: 55)) slideTitle.font = .boldSystemFont(ofSize: 17) slideTitle.textAlignment = .left slideTitle.numberOfLines = 0 slideTitle.lineBreakMode = .byWordWrapping slideTitle.text = lesson.name let txt1 = UILabel.init(frame: CGRect(x: 32, y: 65, width: scrollWidth - 64, height: scrollHeight / 3)) txt1.textAlignment = .left txt1.numberOfLines = 0 txt1.lineBreakMode = .byWordWrapping txt1.text = lesson.desc1[index] var txt2Yposition: CGFloat = 180 if lesson.descImage[index] != "" { let imageView = UIImageView.init(image: UIImage(named: lesson.descImage[index]!)) imageView.frame = CGRect(x: 0, y: 0, width: 200, height: 200) imageView.contentMode = .scaleAspectFit imageView.center = CGPoint(x: scrollWidth/2, y: scrollHeight/2 + 30) slide.addSubview(imageView) txt2Yposition = 430 } let txt2 = UILabel.init(frame: CGRect(x: 32, y: txt2Yposition, width: scrollWidth - 64, height: scrollHeight/3)) txt2.textAlignment = .left txt2.numberOfLines = 0 txt2.lineBreakMode = .byWordWrapping txt2.text = lesson.desc2[index] slide.addSubview(slideImage) slide.addSubview(slideTitle) slide.addSubview(txt1) slide.addSubview(txt2) lessonScrollView.addSubview(slide) } lessonScrollView.contentSize = CGSize(width: scrollWidth * CGFloat(lesson.desc1.count), height: scrollHeight) lessonScrollView.contentSize.height = 1.0 lessonPageControl.numberOfPages = lesson.desc1.count lessonPageControl.currentPage = indexPage } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { setIndicatorForCurrentPage() } func setIndicatorForCurrentPage() { let page = (lessonScrollView.contentOffset.x)/scrollWidth lessonPageControl.currentPage = Int(page) if let lesson = lesson { if Int(page) >= lesson.desc1.count-1 { startChallengButton.setTitle("Start Challenge", for: .normal) } else { startChallengButton.setTitle("Continue", for: .normal) } } } func scrollToPage(page: Int, animated: Bool) { var frame: CGRect = self.lessonScrollView.frame frame.origin.x = frame.size.width * CGFloat(page) frame.origin.y = 0 self.lessonScrollView.scrollRectToVisible(frame, animated: animated) } }
true
2f381274e002af183ed367e98e68a688d5bc1fa0
Swift
ATahhan/CollectionViewChallenge-UdacityConnect
/newcollectionview/ViewController.swift
UTF-8
1,213
2.6875
3
[]
no_license
// // ViewController.swift // newcollectionview // // Created by Waad Alkatheri on 15/01/1440 AH. // Copyright © 1440 Waad Alkatheri. All rights reserved. // import UIKit class ViewController: UIViewController , UICollectionViewDataSource, UICollectionViewDelegate{ // TODO: Go to StoryBoard and add a Third TabBarItem override func viewDidLoad() { super.viewDidLoad() self.demoData() } // TODO: Access your shared model in AppDelegate // TODO: Implement this function to fill the products array with dummy products func demoData() { } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // TODO: return number of Product in your array of products } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // TODO : Dequqe a reusable cell // TODO : Get the corresponding product from the array and pass the data to your cell } }
true
3c6d87bed9c968e2052a204a48ce506791f64196
Swift
ChawlaBhavuk/TransformerApp
/TransformerApp/Model/TransformerModel.swift
UTF-8
1,450
2.8125
3
[ "MIT" ]
permissive
// // TransformerModel.swift // TransformerApp // // Created by Bhavuk Chawla on 16/09/20. // Copyright © 2020 Bhavuk Chawla. All rights reserved. // import Foundation // MARK: - Welcome struct WelcomeTransformers: Codable { let transformers: [Transformer] } // MARK: - Transformer struct Transformer: Codable, Equatable { let courage, endurance, firepower: Int let id: String let intelligence: Int let name: String let rank, skill, speed, strength: Int let team: String let teamIcon: String enum CodingKeys: String, CodingKey { case courage, endurance, firepower, id, intelligence, name, rank, skill, speed, strength, team case teamIcon = "team_icon" } } // MARK: - CustomTransformer struct CustomTransformer { var courage, endurance, firepower: Int? var id: String? var intelligence: Int? var name: String? var rank, skill, speed, strength: Int? var team: String? struct SerializationKeys { static let courage = "courage" static let endurance = "endurance" static let firepower = "firepower" static let id = "id" static let intelligence = "intelligence" static let name = "name" static let rank = "rank" static let skill = "skill" static let speed = "speed" static let strength = "strength" static let team = "team" } } // MARK: - EmptyModel struct EmptyModel: Codable { }
true
470313bab4b5d93c4fde612d9046bd86d8ed9c5f
Swift
atilsamancioglu/1.4.Travel-Map
/Travel Map/InitialVC.swift
UTF-8
3,924
2.5625
3
[]
no_license
// // InitialVC.swift // Travel Map // // Created by Atıl Samancıoğlu on 12/12/2016. // Copyright © 2016 Atıl Samancıoğlu. All rights reserved. // import UIKit import CoreData class InitialVC: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var titleArray = [String]() var subtitleArray = [String]() var latitudeArray = [Double]() var longitudeArray = [Double]() var currentTitle = "" var currentSubtitle = "" var currentLatitude : Double = 0 var currentLongitude : Double = 0 override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self fetchData() } func fetchData() { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Locations") request.returnsObjectsAsFaults = false do { let results = try context.fetch(request) if results.count > 0 { self.titleArray.removeAll(keepingCapacity: false) self.subtitleArray.removeAll(keepingCapacity: false) self.latitudeArray.removeAll(keepingCapacity: false) self.longitudeArray.removeAll(keepingCapacity: false) for result in results as! [NSManagedObject] { if let title = result.value(forKey: "title") as? String { self.titleArray.append(title) } if let subtitle = result.value(forKey: "subtitle") as? String { self.subtitleArray.append(subtitle) } if let latitude = result.value(forKey: "latitude") as? Double { self.latitudeArray.append(latitude) } if let longitude = result.value(forKey: "longitude") as? Double { self.longitudeArray.append(longitude) } self.tableView.reloadData() } } } catch { } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titleArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = titleArray[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.currentTitle = self.titleArray[indexPath.row] self.currentSubtitle = self.subtitleArray[indexPath.row] self.currentLatitude = self.latitudeArray[indexPath.row] self.currentLongitude = self.longitudeArray[indexPath.row] performSegue(withIdentifier: "toMapSegue", sender: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "toMapSegue" { let destinationVC = segue.destination as! ViewController destinationVC.transmittedTitle = self.currentTitle destinationVC.transmittedSubtitle = self.currentSubtitle destinationVC.transmittedLatitude = self.currentLatitude destinationVC.transmittedLongitude = self.currentLongitude } } @IBAction func addButtonClicked(_ sender: Any) { performSegue(withIdentifier: "toMapSegue", sender: nil) } }
true
9e8260f669f4863e629518b4b347a7a2c0174b92
Swift
billbill96/loancalculator
/LoanCalculator/Modules/MyLoan/MyLoanInteractor.swift
UTF-8
789
2.640625
3
[]
no_license
// // MyLoanInteractor.swift // LoanCalculator // // Created by Supannee Mutitanon on 21/8/20. // Copyright © 2020 Supannee Mutitanon. All rights reserved. // import Foundation import Alamofire class MyLoanInteractor: MyLoanteractorInputProtocol { var presenter: MyLoanInteractorOutputProtocol? let dataManager: DataManagerProtocol init(dataManager: DataManagerProtocol = DataManager()) { self.dataManager = dataManager } func getLoanList() { dataManager.getLoanList().done { [weak self] model in guard let self = self else { return } self.presenter?.getLoanListSuccess(loanList: model) }.catch { [weak self] error in guard let self = self else { return } self.presenter?.getLoanListFail() } } }
true
b00761fbf61a3121c89e384b1b12d5bcc6bbb765
Swift
bunkersmith/Swift-Music-Player
/Swift Music Player/Audio Handling/AudioSessionManager.swift
UTF-8
1,836
2.546875
3
[]
no_license
// // AudioSessionManager.swift // Swift Music Player // // Created by CarlSmith on 6/25/15. // Copyright (c) 2015 CarlSmith. All rights reserved. // import UIKit import AVFoundation import MediaPlayer class AudioSessionManager: NSObject { fileprivate var audioSessionPtr = AVAudioSession.sharedInstance() fileprivate var remoteAudioCommandHandler = RemoteAudioCommandHandler.instance fileprivate var audioNotificationHandler = AudioNotificationHandler.instance // Singleton instance static let instance = AudioSessionManager() fileprivate override init() { super.init() } deinit { Logger.logDetails(msg: "Calling deactivateAudioSession") deactivateAudioSession() } func activateAudioSession() { Logger.logDetails(msg: "Entered") do { try audioSessionPtr.setCategory(AVAudioSessionCategoryPlayback) } catch let error as NSError { Logger.writeToLogFile("Error setting audio session category: \(error)") } do { try audioSessionPtr.setActive(true) } catch let error as NSError { Logger.writeToLogFile("Error setting audio session to active: \(error)") } audioNotificationHandler.addNotificationObservers() remoteAudioCommandHandler.enableDisableRemoteCommands(true) } func deactivateAudioSession() { Logger.logDetails(msg: "Entered") do { try audioSessionPtr.setActive(false) } catch let error as NSError { Logger.writeToLogFile("Error deactivating audio session: \(error)") } audioNotificationHandler.removeNotificationObservers() remoteAudioCommandHandler.enableDisableRemoteCommands(false) } }
true
ea7b06dc51162f82b5a766602d1e0be9cf1eee13
Swift
eduregis/B.E.E.P.
/B.E.E.P./Components/SpriteComponent.swift
UTF-8
877
3.203125
3
[]
no_license
import SpriteKit import GameplayKit class SpriteComponent: GKComponent { // criamos uma variável que receberá o sprite let node: SKSpriteNode // criamos um construtor caso o tmanho da imagem seja o mesmo em que ele deva aparecer na tela init(texture: SKTexture, name: String) { node = SKSpriteNode(texture: texture, color: .white, size: texture.size()) node.name = name super.init() } // criamos um contrutor que também recebe um tamanho, caso precisemos redimensionar o sprite init(texture: SKTexture, size: CGSize, name: String) { node = SKSpriteNode(texture: texture, color: .white, size: size) node.name = name super.init() } // construtor padrão de erro required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
1064d0fd8fdcb8f4a75ac1237b7ada3b35735eb8
Swift
azat-dev/ios-bullseye
/BullseyeTests/BullseyeTests.swift
UTF-8
1,978
2.984375
3
[]
no_license
// // BullseyeTests.swift // BullseyeTests // // Created by Azat Kaiumov on 17.04.2021. // import XCTest @testable import Bullseye class BullseyeTests: XCTestCase { var game: Game! override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. game = Game() } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. game = nil } func testScorePositive() throws { let guess = game.target + 5 let points = game.points(value: guess) XCTAssertEqual(points, 95) } func testScoreNegative() throws { let guess = game.target - 5 let points = game.points(value: guess) XCTAssertEqual(points, 95) } func testScoreExact() throws { let guess = game.target let points = game.points(value: guess) XCTAssertEqual(points, 100 + 100) } func testScoreWithoutOne() throws { let guess = game.target > 0 ? game.target - 1 : game.target + 1 let points = game.points(value: guess) XCTAssertEqual(points, 99 + 50) } func testStartNewRound() throws { XCTAssertEqual(game.score, 0) XCTAssertEqual(game.round, 1) game.startNewRound(points: 100) XCTAssertEqual(game.score, 100) XCTAssertEqual(game.round, 2) game.startNewRound(points: 50) XCTAssertEqual(game.score, 150) XCTAssertEqual(game.round, 3) } func testRestartGame() throws { game.startNewRound(points: 100) XCTAssertNotEqual(game.round, 1) XCTAssertNotEqual(game.score, 0) game.restart() XCTAssertEqual(game.round, 1) XCTAssertEqual(game.score, 0) } }
true
794012b1b51144989cbdb32f5a34483a6a488831
Swift
isabella232/android-auto-companion-ios
/Sources/AndroidAutoConnectedDeviceManagerMocks/SecureSessionManagerMock.swift
UTF-8
1,610
2.65625
3
[ "Apache-2.0" ]
permissive
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation @testable import AndroidAutoConnectedDeviceManager /// A mock `SecureSessionManager` that allows the secure session to be set and returned. public class SecureSessionManagerMock: SecureSessionManager { public var secureSessions: [String: Data] = [:] /// The return value `storeSecureSession(_:for:)`. `true` indicates that that method succeeds. public var storeSecureSessionSucceeds = true public init() {} public func secureSession(for identifier: String) -> Data? { return secureSessions[identifier] } public func storeSecureSession(_ secureSession: Data, for identifier: String) -> Bool { guard storeSecureSessionSucceeds else { return false } secureSessions[identifier] = secureSession return true } public func clearSecureSession(for identifier: String) { secureSessions[identifier] = nil } /// Resets back to the default initialization state. public func reset() { secureSessions = [:] storeSecureSessionSucceeds = true } }
true
e34c3bdcba5b93d711f8baac12ae8ad52a11eb14
Swift
greatmm/myLessons
/swiftBase/lesson_0/lesson_13/main.swift
UTF-8
8,234
4.1875
4
[]
no_license
// // main.swift // lesson_13 // // Created by greatkk on 2019/5/28. // Copyright © 2019 greatkk. All rights reserved. // import Foundation /* 通过定义构造器来实现构造过程,这些构造器可以看做是用来创建特定类型新实例的特殊方法。与 Objective-C 中的构造器不同,Swift 的构造器无需返回值,它们的主要任务是保证新实例在第一次使用前完成正确的初始化。 当你为存储型属性设置默认值或者在构造器中为其赋值时,它们的值是被直接设置的,不会触发任何属性观察者 */ //init() { // // 在此处执行构造过程 //} struct Fahrenheit { var temperature = 32.0 init() { temperature = 32.0 } } var f = Fahrenheit() print("The default temperature is \(f.temperature)° Fahrenheit") // 打印 "The default temperature is 32.0° Fahrenheit struct Celsius { var temperatureInCelsius: Double init(fromFahrenheit fahrenheit: Double) { temperatureInCelsius = (fahrenheit - 32.0) / 1.8 } init(fromKelvin kelvin: Double) { temperatureInCelsius = kelvin - 273.15 } } let boilingPointOfWater = Celsius(fromFahrenheit: 212.0) // boilingPointOfWater.temperatureInCelsius 是 100.0 let freezingPointOfWater = Celsius(fromKelvin: 273.15) // freezingPointOfWater.temperatureInCelsius 是 0.0 struct Color { let red, green, blue: Double init(red: Double, green: Double, blue: Double) { self.red = red self.green = green self.blue = blue } init(white: Double) { red = white green = white blue = white } } //如果结构体或类的所有属性都有默认值,同时没有自定义的构造器,那么 Swift 会给这些结构体或类提供一个默认构造器(default initializers)。这个默认构造器将简单地创建一个所有属性值都设置为默认值的实例。 //class ShoppingListItem { // var name: String? // var quantity = 1 // var purchased = false //} //var item = ShoppingListItem() //对于值类型,你可以使用self.init在自定义的构造器中引用相同类型中的其它构造器。并且你只能在构造器内部调用self.init。如果你为某个值类型定义了一个自定义的构造器,你将无法访问到默认构造器(如果是结构体,还将无法访问逐一成员构造器)。这种限制可以防止你为值类型增加了一个额外的且十分复杂的构造器之后,仍然有人错误的使用自动生成的构造器 //注意,假如你希望默认构造器、逐一成员构造器以及你自己的自定义构造器都能用来创建实例,可以将自定义的构造器写到扩展(extension)中,而不是写在值类型的原始定义中。 //每一个类都必须拥有至少一个指定构造器。在某些情况下,许多类通过继承了父类中的指定构造器而满足了这个条件。 /* 类的指定构造器的写法跟值类型简单构造器一样: init(parameters) { statements } 便利构造器也采用相同样式的写法,但需要在init关键字之前放置convenience关键字,并使用空格将它们俩分开: convenience init(parameters) { statements } */ /* 类的构造器代理规则 为了简化指定构造器和便利构造器之间的调用关系,Swift 采用以下三条规则来限制构造器之间的代理调用: 规则 1 指定构造器必须调用其直接父类的的指定构造器。 规则 2 便利构造器必须调用同类中定义的其它构造器。 规则 3 便利构造器必须最终导致一个指定构造器被调用。 一个更方便记忆的方法是: 指定构造器必须总是向上代理 便利构造器必须总是横向代理 */ /* 一个对象的内存只有在其所有存储型属性确定之后才能完全初始化。为了满足这一规则,指定构造器必须保证它所在类引入的属性在它往上代理之前先完成初始化。 */ //跟 Objective-C 中的子类不同,Swift 中的子类默认情况下不会继承父类的构造器。Swift 的这种机制可以防止一个父类的简单构造器被一个更精细的子类继承,并被错误地用来创建子类的实例。 class Vehicle { var numberOfWheels = 0 var description: String { return "\(numberOfWheels) wheel(s)" } } class Bicycle: Vehicle { override init() { super.init() numberOfWheels = 2 } } //Bicycle的构造器init()以调用super.init()方法开始,这个方法的作用是调用Bicycle的父类Vehicle的默认构造器。这样可以确保Bicycle在修改属性之前,它所继承的属性numberOfWheels能被Vehicle类初始化。在调用super.init()之后,属性numberOfWheels的原值被新值2替换。 class Food { var name: String init(name: String) { self.name = name } convenience init() { self.init(name: "[Unnamed]") } } class RecipeIngredient: Food { var quantity: Int init(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) } override convenience init(name: String) { self.init(name: name, quantity: 1) } } class ShoppingListItem: RecipeIngredient { var purchased = false var description: String { var output = "\(quantity) x \(name)" output += purchased ? " ✔" : " ✘" return output } } //严格来说,构造器都不支持返回值。因为构造器本身的作用,只是为了确保对象能被正确构造。因此你只是用return nil表明可失败构造器构造失败,而不要用关键字return来表明构造成功 struct Animal { let species: String init?(species: String) { if species.isEmpty { return nil } self.species = species } } let someCreature = Animal(species: "Giraffe") // someCreature 的类型是 Animal? 而不是 Animal //enum TemperatureUnit { // case Kelvin, Celsius, Fahrenheit // init?(symbol: Character) { // switch symbol { // case "K": // self = .Kelvin // case "C": // self = .Celsius // case "F": // self = .Fahrenheit // default: // return nil // } // } //} enum TemperatureUnit: Character { case Kelvin = "K", Celsius = "C", Fahrenheit = "F" } let fahrenheitUnit = TemperatureUnit(rawValue: "F") class Product { let name: String init?(name: String) { if name.isEmpty { return nil } self.name = name } } class CartItem: Product { let quantity: Int init?(name: String, quantity: Int) { if quantity < 1 { return nil } self.quantity = quantity super.init(name: name) } } class Document { var name: String? // 该构造器创建了一个 name 属性的值为 nil 的 document 实例 init() {} // 该构造器创建了一个 name 属性的值为非空字符串的 document 实例 init?(name: String) { self.name = name if name.isEmpty { return nil } } } class AutomaticallyNamedDocument: Document { override init() { super.init() self.name = "[Untitled]" } override init(name: String) { super.init() if name.isEmpty { self.name = "[Untitled]" } else { self.name = name } } } //必要构造器,在类的构造器前添加required修饰符表明所有该类的子类都必须实现该构造器: class SomeClass { required init() { // 构造器的实现代码 } } /* 在子类重写父类的必要构造器时,必须在子类的构造器前也添加required修饰符,表明该构造器要求也应用于继承链后面的子类。在重写父类中必要的指定构造器时,不需要添加override修饰符: class SomeSubclass: SomeClass { required init() { // 构造器的实现代码 } } */ //通过闭包或函数设置属性的默认值 //class SomeClass { // let someProperty: SomeType = { // // 在这个闭包中给 someProperty 创建一个默认值 // // someValue 必须和 SomeType 类型相同 // return someValue // }() //}
true
37d0cbe22b8cf474206a3d8417e83dda39f878d3
Swift
mohsinalimat/AutoAdjust
/autoadjust.swift
UTF-8
1,361
2.65625
3
[ "MIT" ]
permissive
// // AutoAdjust.swift // AutoAdjust // // Created by Jonathan Fritz on 05.09.18. // Copyright © 2018 Jonathan Fritz Noscio IT-Servicedienstleistungen. All rights reserved. // import Foundation import UIKit extension UITableView { // I am working on a way to deinit the observers when the tableview also is deiniting. // If you have ideas, feel free to help out! func setupAutoAdjust() { NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardshown), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardhide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } @objc func keyboardshown(_ notification:Notification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { self.fitContentInset(inset: UIEdgeInsetsMake(0, 0, keyboardSize.height, 0)) } } @objc func keyboardhide(_ notification:Notification) { if ((notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil { self.fitContentInset(inset: .zero) } } func fitContentInset(inset:UIEdgeInsets!) { self.contentInset = inset self.scrollIndicatorInsets = inset } }
true
c3678c27db23b2680652ae1f7807200efd4892da
Swift
hori-imuuzak/ios_instagram_clone
/InstagramClone/src/domain/models/RegisterUser.swift
UTF-8
721
2.6875
3
[]
no_license
// // RegisterUser.swift // InstagramClone // // Created by 堀知海 on 2020/05/07. // Copyright © 2020 umichan. All rights reserved. // class RegisterUser { let email: String! let password: String! let displayName: String! init(email: String, password: String, displayName: String) throws { if email.isEmpty { throw ModelError.illegalArgument("email") } if password.isEmpty { throw ModelError.illegalArgument("password") } if displayName.isEmpty { throw ModelError.illegalArgument("displayName") } self.email = email self.password = password self.displayName = displayName } }
true
1a4b7d2d56a7c022b4061c999c7afd7c71e2fed2
Swift
MrOgeid/ACHNBrowserUI
/ACHNBrowserUI/ACHNBrowserUI/views/mysteryIslands/MysteryIslandRow.swift
UTF-8
1,629
2.84375
3
[ "Apache-2.0" ]
permissive
// // MysteryIslandRow.swift // ACHNBrowserUI // // Created by Thomas Ricouard on 17/05/2020. // Copyright © 2020 Thomas Ricouard. All rights reserved. // import SwiftUI import Backend struct MysteryIslandRow: View { let island: MysteryIsland var body: some View { HStack { Image(island.image) .resizable() .frame(width: 75, height: 75) .cornerRadius(8) VStack(alignment: .leading, spacing: 4) { Text(LocalizedStringKey(island.name)) .style(appStyle: .rowTitle) HStack(spacing: 0) { Text("\(island.chance)% chance") .style(appStyle: .rowDescription) island.max_visit.map { visits in Text(" - max \(visits) visit") .style(appStyle: .rowDescription) } } Text("Flowers: \(NSLocalizedString(island.flowers.capitalized, comment: ""))") .style(appStyle: .rowDescription) Text("Trees: \(NSLocalizedString(island.trees.capitalized, comment: ""))") .style(appStyle: .rowDescription) } } } } struct MysteryIslandRow_Previews: PreviewProvider { static var previews: some View { NavigationView { List { MysteryIslandRow(island: MysteryIsland.loadMysteryIslands()!.randomElement()!) } .listStyle(InsetGroupedListStyle()) } .previewLayout(.fixed(width: 375, height: 500)) } }
true
d7e8277308617fa8af0004a49b9221ab5c17bf7e
Swift
simajune/iOS_School
/SourceCode/171107_MapKit/171107_MapKit/ViewController.swift
UTF-8
2,749
2.75
3
[]
no_license
// // ViewController.swift // 171107_MapKit // // Created by SIMA on 2017. 11. 7.. // Copyright © 2017년 SimaDev. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController, MKMapViewDelegate{ let manager = CLLocationManager() @IBOutlet var mapView: MKMapView! var annotation: MKAnnotation? override func viewDidLoad() { super.viewDidLoad() let location = CLLocation(latitude: 37.515675, longitude: 127.021378) let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1) let coordinateRegion = MKCoordinateRegionMake(location.coordinate, span) mapView.setRegion(coordinateRegion, animated: true) mapView.delegate = self let customPin = CustomAnnotation(title: "Sample", coordinate: location.coordinate) mapView.addAnnotation(customPin) manager.delegate = self manager.requestWhenInUseAuthorization() manager.requestAlwaysAuthorization() manager.desiredAccuracy = kCLLocationAccuracyBest manager.startUpdatingLocation() } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if let annotation = annotation as? CustomAnnotation { let identity = "pin" var pinView: MKPinAnnotationView if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identity) as? MKPinAnnotationView { dequeuedView.annotation = annotation pinView = dequeuedView } else { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identity) pinView.canShowCallout = true pinView.calloutOffset = CGPoint(x: -5, y: 5) pinView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) as UIView } return pinView } return nil } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { ///callout Action } } class CustomAnnotation:NSObject, MKAnnotation { var coordinate: CLLocationCoordinate2D var title: String? var subtitle: String? init(title: String, coordinate: CLLocationCoordinate2D) { self.title = title self.coordinate = coordinate } } extension ViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let nowLocation = locations.last { manager.startUpdatingLocation() } } }
true
31fed860ace4dfa410f743c432546e87233ff96d
Swift
colejd/SwiftUI-Shapes
/Sources/Shapes/OmniRectangle/CornerStyle.swift
UTF-8
5,413
3.171875
3
[ "MIT" ]
permissive
// Swift toolchain version 5.0 // Running macOS version 10.15 // Created on 11/13/20. // // Author: Kieran Brown // import SwiftUI extension OmniRectangle { public enum CornerStyle { case round(radius: CGFloat) case cut(depth: CGFloat) case square } } extension OmniRectangle.CornerStyle { func applyTopRight(_ path: inout Path, _ width: CGFloat, _ height: CGFloat) -> Void { let checkMin: (CGFloat) -> CGFloat = { min(min($0, height/2), width/2) } switch self { case .round(radius: let radius): path.move(to: CGPoint(x: width - checkMin(radius), y: 0)) path.addArc( center: CGPoint(x: width - checkMin(radius), y: checkMin(radius)), radius: checkMin(radius), startAngle: Angle(radians: -.pi/2), endAngle: .zero, clockwise: false ) case .cut(depth: let depth): path.move(to: CGPoint(x: width-checkMin(depth), y: 0)) path.addLine(to: CGPoint(x: width, y: checkMin(depth))) case .square: path.move(to: CGPoint(x: width, y: 0)) } } func applyBottomRight(_ path: inout Path, _ width: CGFloat, _ height: CGFloat, _ curvature: CGFloat) -> Void { let checkMin: (CGFloat) -> CGFloat = { min(min($0, height/2), width/2) } switch self { case .round(radius: let radius): path.addQuadCurve(to: CGPoint(x: width, y: height - checkMin(radius)), control: CGPoint(x: width - width*curvature/2, y: height/2)) path.addArc( center: CGPoint(x: width - checkMin(radius) , y: height - checkMin(radius)), radius: checkMin(radius), startAngle: .zero, endAngle: Angle(radians: .pi/2), clockwise: false ) case .cut(depth: let depth): path.addQuadCurve(to: CGPoint(x: width, y: height-checkMin(depth)), control: CGPoint(x: width - width*curvature/2, y: height/2)) path.addLine(to: CGPoint(x: width-checkMin(depth), y: height)) case .square: path.addQuadCurve(to: CGPoint(x: width, y: height), control: CGPoint(x: width - width*curvature/2, y: height/2)) } } func applyBottomLeft(_ path: inout Path, _ width: CGFloat, _ height: CGFloat, _ curvature: CGFloat) -> Void { let checkMin: (CGFloat) -> CGFloat = { min(min($0, height/2), width/2) } switch self { case .round(radius: let radius): path.addQuadCurve(to: CGPoint(x: checkMin(radius), y: height), control: CGPoint(x: width/2, y: height - height*curvature/2)) path.addArc( center: CGPoint(x: checkMin(radius), y: height - checkMin(radius)), radius: checkMin(radius), startAngle: Angle(radians: .pi/2), endAngle: Angle(radians: .pi), clockwise: false ) case .cut(depth: let depth): path.addQuadCurve(to: CGPoint(x: checkMin(depth), y: height), control: CGPoint(x: width/2, y: height - height*curvature/2)) path.addLine(to: CGPoint(x: 0, y: height-checkMin(depth))) case .square: path.addQuadCurve(to: CGPoint(x: 0, y: height), control: CGPoint(x: width/2, y: height - height*curvature/2)) } } func applyTopLeft(_ path: inout Path, _ width: CGFloat, _ height: CGFloat, _ curvature: CGFloat) -> Void { let checkMin: (CGFloat) -> CGFloat = { min(min($0, height/2), width/2) } switch self { case .round(radius: let radius): path.addQuadCurve(to: CGPoint(x: 0, y: checkMin(radius)), control: CGPoint(x: width*curvature/2, y: height/2)) path.addArc( center: CGPoint(x: checkMin(radius), y: checkMin(radius)), radius: checkMin(radius), startAngle: Angle(radians: .pi), endAngle: Angle(radians: 3*Double.pi/2), clockwise: false ) case .cut(depth: let depth): path.addQuadCurve(to: CGPoint(x: 0, y: checkMin(depth)), control: CGPoint(x: width*curvature/2, y: height/2)) path.addLine(to: CGPoint(x: checkMin(depth), y: 0)) case .square: path.addQuadCurve(to: CGPoint(x: 0, y: 0), control: CGPoint(x: width*curvature/2, y: height/2)) } } } extension OmniRectangle.CornerStyle: CustomStringConvertible { static let formatter: NumberFormatter = { let f = NumberFormatter() f.maximumFractionDigits = 3 return f }() public var description: String { switch self { case .round(radius: let radius): return "radius: \(Self.formatter.string(from: radius as NSNumber) ?? "")" case .cut(depth: let depth): return "depth: \(Self.formatter.string(from: depth as NSNumber) ?? "")" case .square: return "square" } } }
true
57f143530f122e3dcc7eb9c9ad492ef070429868
Swift
iMoment/BreakPoint-App
/BreakPoint/View/UserCell.swift
UTF-8
1,139
2.703125
3
[]
no_license
// // UserCell.swift // BreakPoint // // Created by Stanley Pan on 26/09/2017. // Copyright © 2017 Stanley Pan. All rights reserved. // import UIKit class UserCell: UITableViewCell { // MARK: Outlets @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var emailLabel: UILabel! @IBOutlet weak var checkImageView: UIImageView! // MARK: Variables var isShowing = false func configureCell(profileImage image: UIImage, email: String, isSelected: Bool) { self.profileImageView.image = image self.emailLabel.text = email if isSelected { self.checkImageView.isHidden = false } else { self.checkImageView.isHidden = true } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if selected { if isShowing == false { checkImageView.isHidden = false isShowing = true } else { checkImageView.isHidden = true isShowing = false } } } }
true
a8397e611f706816d63034647a9fcbc14e291a96
Swift
frobledo/Advanced-Mobile-App---Robledo
/Grad Project/Milestone 3/PenguinHealth/PhysicsCategory.swift
UTF-8
431
2.765625
3
[]
no_license
// // PhysicsCategory.swift // PenguinHealth // // Created by Fuji Robledo on 4/23/17. // Copyright © 2017 Fuji Robledo. All rights reserved. // import Foundation //Establishing constants for physics categories struct PhysicsCategory { static let None : UInt32 = 0 static let All : UInt32 = UInt32.max static let Food : UInt32 = 0b1 static let Poison : UInt32 = 0b10 static let Penguin : UInt32 = 0b111 }
true
97b0d0123b9ae6f3b0b48391974750e2b56f214c
Swift
lopezjosed89/TheMovieDB
/TheMovieDB/TheMovieDB/MyPlayground.playground/Contents.swift
UTF-8
1,279
3.109375
3
[ "MIT" ]
permissive
//: Playground - noun: a place where people can play import UIKit import Alamofire import PlaygroundSupport //PlaygroundPage.current.needsIndefiniteExecution = true let nowPlaying = "https://api.themoviedb.org/3/movie/now_playing?api_key=a86dbf84324001b2221400d5f138500c&language=en-US&page=1" let popular = "https://api.themoviedb.org/3/movie/popular?api_key=a86dbf84324001b2221400d5f138500c&language=en-US&page=1" let topRated = "https://api.themoviedb.org/3/movie/top_rated?api_key=a86dbf84324001b2221400d5f138500c&language=en-US&page=1" let upComing = "https://api.themoviedb.org/3/movie/upcoming?api_key=a86dbf84324001b2221400d5f138500c&language=en-US&page=1" func jsonParser(JSON: Any) -> Void { if let dictionary = JSON as? [String: Any]{ if let nestedDictionary = dictionary["results"] as? [[String: Any]]{ for result in nestedDictionary { print(result["poster_path"]!) } } } } func requestMovie(upComing: String) -> Void { Alamofire.request(upComing).responseJSON { (response) -> Void in // check if has a value if let JSON = response.result.value { jsonParser(JSON: JSON) print(JSON) } PlaygroundPage.current.finishExecution() } } requestMovie(upComing: upComing)
true
fb5a0c17311a2387e8e3a7c77e7506c16d2ff7a5
Swift
priyaakhauri/ConatctPicker
/ContactDemoApp/SearchPageView.swift
UTF-8
7,616
2.71875
3
[]
no_license
// // SearchPageView.swift // ContactDemoApp // // Created by Priya on 23/06/18. // Copyright © 2018 DemoApp. All rights reserved. // import Foundation import UIKit import CoreData class SearchPageView : UIViewController,UISearchBarDelegate { @IBOutlet weak var tableViewVar: UITableView! var firstName : UITextField? = nil var secondName : UITextField? = nil var emailVar : UITextField? = nil var phoneNum : UITextField? = nil var countryName : UITextField? = nil var keyboradHideforEditNoteVarRem : UIBarButtonItem! @IBOutlet weak var mySearchBar: UISearchBar! func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String){ print(searchText) if(searchText == "") { let predicate = NSPredicate(format: "completed == FALSE") fetchedResultsController.fetchRequest.predicate = predicate } else { let predicate = NSPredicate(format: "firstname contains[c] %@ || secondname contains[c] %@", searchText, searchText) fetchedResultsController.fetchRequest.predicate = predicate } // Set the created predicate to our fetch request. do { // Perform the initial fetch to Core Data. // After this step, the fetched results controller // will only retrieve more records if necessary. try fetchedResultsController.performFetch() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } self.tableViewVar.reloadData() } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { self.navigationItem.rightBarButtonItem = self.keyboradHideforEditNoteVarRem } @IBAction func hideKeyboardBtnFunc(_ sender: UIBarButtonItem) { if(self.navigationItem.rightBarButtonItem != nil) { keyboradHideforEditNoteVarRem = self.navigationItem.rightBarButtonItem self.navigationItem.rightBarButtonItem = nil } self.mySearchBar.endEditing(true) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) if(self.navigationItem.rightBarButtonItem != nil) { keyboradHideforEditNoteVarRem = self.navigationItem.rightBarButtonItem self.navigationItem.rightBarButtonItem = nil } } override func viewDidLoad() { super.viewDidLoad() mySearchBar.delegate = self let searchTextField:UITextField = mySearchBar.subviews[0].subviews.last as! UITextField searchTextField.layer.cornerRadius = 15 searchTextField.textAlignment = NSTextAlignment.left } var _fetchedResultsController: NSFetchedResultsController<ContactDetails>? = nil // The proxy variable to serve as a lazy getter to our // fetched results controller. var fetchedResultsController: NSFetchedResultsController<ContactDetails> { let appDel = UIApplication.shared.delegate as? AppDelegate // If the variable is already initialized we return that instance. if _fetchedResultsController != nil { return _fetchedResultsController! } // If not lets build the required elements for the fetched // results controller. // First we need to create a fetch request with the pretended type. let fetchRequest: NSFetchRequest<ContactDetails> = ContactDetails.fetchRequest() // Set the batch size to a suitable number (optional). fetchRequest.fetchBatchSize = 20 // Create at least one sort order attribute and type (ascending\descending) let sortDescriptor = NSSortDescriptor(key: "firstname", ascending: true) // Set the sort objects to the fetch request. fetchRequest.sortDescriptors = [sortDescriptor] // Optionally, let's create a filter\predicate. // The goal of this predicate is to fetch Tasks that are not yet completed. let predicate = NSPredicate(format: "completed == FALSE") // Set the created predicate to our fetch request. fetchRequest.predicate = predicate // Create the fetched results controller instance with the defined attributes. let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: (appDel?.managedObjectContext)!, sectionNameKeyPath: nil, cacheName: nil) // Set the delegate of the fetched results controller to the view controller. // with this we will get notified whenever occours changes on the data. aFetchedResultsController.delegate = self // Setting the created instance to the view controller instance. _fetchedResultsController = aFetchedResultsController do { // Perform the initial fetch to Core Data. // After this step, the fetched results controller // will only retrieve more records if necessary. try _fetchedResultsController!.performFetch() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } return _fetchedResultsController! } } extension SearchPageView : NSFetchedResultsControllerDelegate { func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { // Whenever a change occours on our data, we refresh the table view. self.tableViewVar.reloadData() } } extension SearchPageView : UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // We will use the proxy variable to our fetcehed results // controller and from that we try to get from that section // index access to the number of objects available. // If not possible, we will ignore and return 0 objects. return self.fetchedResultsController.sections?[section].numberOfObjects ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // First we get a cell from the table view with the identifier "Cell" let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) // Then we get the object at the current index from the fetched results controller let task = self.fetchedResultsController.object(at: indexPath) // And update the cell label with the task name cell.backgroundColor = UIColor.white cell.textLabel?.text = task.firstname! + " " + task.secondname! // Finally we return the updated cell return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let appDel = UIApplication.shared.delegate as? AppDelegate guard let _context = appDel?.managedObjectContext else { return } let managedObject = self.fetchedResultsController.object(at: indexPath) _context.delete(managedObject) appDel?.saveContext() } } }
true
00cfd5ea2c997e7f60a4c2f6ae372e7f639a8e5c
Swift
OguzDm/Exercism
/list-ops/Sources/ListOps/ListOps.swift
UTF-8
1,778
3.265625
3
[]
no_license
struct ListOps { static func append<T>(_ array1: [T], _ array2: [T]) -> [T] { var appendedArray = array1 for i in array2 { appendedArray.append(i) } return appendedArray } static func concat<T>(_ arrays: [T]...) -> [T] { var concat = [T]() for array in arrays { concat = append(concat, array) } return concat } static func filter<T>(_ array: [T], isIncluded: ((T) -> Bool)) -> [T] { var filteredArray = [T]() for i in array { if isIncluded(i) == true { filteredArray.append(i) } } return filteredArray } static func length<T>(_ array: [T]) -> Int { var count = 0 for _ in array { count += 1 } return count } static func map<T>(_ array: [T], transform: ((T) -> T)) -> [T] { var mappedArray = [T]() mappedArray.reserveCapacity(length(array)) for i in array { mappedArray.append(transform(i)) } return mappedArray } static func foldLeft<T>(_ array: [T], accumulated: T, combine: ((T, T) -> T)) -> T { var result = accumulated for i in array { result = combine(result, i) } return result } static func foldRight<T>(_ array: [T], accumulated: T, combine: ((T, T) -> T)) -> T { var result = accumulated for i in array.reversed() { result = combine(i, result) } return result } static func reverse<T>(_ array: [T]) -> [T] { var result = [T]() for i in array { result.insert(i, at: 0) } return result } }
true
c47c4d05648895bb4236318f9c0ea1dba199cc42
Swift
splsylp/LPStretchableHeaderView
/LPStretchableHeaderView/LPStretchableHeaderView.swift
UTF-8
1,222
2.875
3
[]
no_license
// // LPStretchableHeaderView.swift // LPStretchableHeaderView // // Created by Tony on 2017/8/23. // Copyright © 2017年 Tony. All rights reserved. // import UIKit public class LPStretchableHeaderView: NSObject { private var stretchView = UIView() private var imageRatio: CGFloat private var originFrame = CGRect() public init(stretchableView: UIView) { stretchView = stretchableView originFrame = stretchableView.frame imageRatio = stretchableView.bounds.height / stretchableView.bounds.width } public func scrollViewDidScroll(_ scrollView: UIScrollView) { let yOffset = scrollView.contentOffset.y if yOffset > 0 { // 往上移动 var frame = originFrame frame.origin.y = originFrame.origin.y - yOffset stretchView.frame = frame } else { // 往下移动 var frame = originFrame frame.size.height = originFrame.size.height - yOffset frame.size.width = frame.size.height / imageRatio frame.origin.x = originFrame.origin.x - (frame.size.width - originFrame.size.width) * 0.5 stretchView.frame = frame } } }
true
358ea0ef9dea92ec5feb05854d5616a32ae7e080
Swift
skleung/equations
/equations/GameViewController.swift
UTF-8
8,708
2.65625
3
[]
no_license
// // GameViewController.swift // equations // // Created by Sherman Leung on 7/29/15. // Copyright (c) 2015 Khan Academy. All rights reserved. // import UIKit class GameViewController: UIViewController, UIViewControllerTransitioningDelegate { var tileSpacing:CGFloat = 15 let ScreenHeight = UIScreen.mainScreen().bounds.height var allowedTiles:[TileView] = [] var requiredTiles:[TileView] = [] var allowedChars:String = "23+4" var requiredChars:String = "125+" var goalChars:String = "2*4" var solutionTiles:[TileView] = [] var goalTiles:[TileView] = [] var tileSide:CGFloat = 30 var startingPanPoint:CGPoint = CGPointZero @IBOutlet var allowedArea: UIView! @IBOutlet var solutionArea: UIView! @IBOutlet var goalArea: UIView! override func viewDidLoad() { renderBoard() } func renderBoard() { tileSide = ceil(UIScreen.mainScreen().bounds.width * 0.9 / CGFloat(max(count(allowedChars),count(requiredChars))) - tileSpacing) tileSpacing = 0.25*tileSide allowedTiles = renderArea(allowedArea, chars: allowedChars, required: false, isSolution: false) requiredTiles = renderArea(solutionArea, chars: requiredChars, required: true, isSolution: false) renderArea(goalArea, chars: goalChars, required: false, isSolution: true) adjustGoalTiles(goalTiles, area: goalArea) } private func renderArea(area: UIView, chars:String, required:Bool, isSolution: Bool) -> [TileView] { //get the left margin for first tile var tiles:[TileView] = []; var xOffset = tileSide*0.75 if (isSolution) { xOffset *= 0.25 } var yOffset = area.frame.origin.y + area.frame.size.height if (isSolution) { yOffset -= area.frame.size.height/2.0 } //adjust for tile center (instead of the tile's origin) for (index, letter) in enumerate(chars) { var color = UIColor.tealColor() if (required) { color = UIColor.grapefruitColor() } else if (isSolution) { color = UIColor.goldenrodColor() } let tile = TileView(letter: letter, sideLength: tileSide, required: required, color: color) tile.center = CGPointMake(xOffset, yOffset) xOffset += (tile.frame.width + tileSpacing) if (!isSolution) { let panGesture = UIPanGestureRecognizer(target: self, action: "tilePan:") tile.addGestureRecognizer(panGesture) // pinch recognizer let pinchRecognizer = UIPinchGestureRecognizer(target: self, action: "pinchTile:") tile.addGestureRecognizer(pinchRecognizer) } if (isSolution) { tile.layer.borderColor = UIColor.goldenrodColor().CGColor } // add views self.view.addSubview(tile) if (required) { solutionTiles.append(tile) } if (isSolution) { goalTiles.append(tile) } tiles.append(tile) } return tiles } func pinchTile(sender: UIPinchGestureRecognizer) { if let view = sender.view { view.transform = CGAffineTransformScale(view.transform, sender.scale, sender.scale) sender.scale = 1.0 } } func tilePan(recognizer: UIPanGestureRecognizer) { var point = recognizer.locationInView(self.view) var tileView = recognizer.view as! TileView switch recognizer.state { case .Began: startingPanPoint = tileView.center tileView.pop_addAnimation(createSpringAnimation(1.25), forKey: "springAnimation") case .Changed, .Cancelled: var dx = recognizer.translationInView(self.view).x var dy = recognizer.translationInView(self.view).y tileView.center = CGPoint(x: tileView.center.x + dx, y: tileView.center.y + dy) recognizer.setTranslation(CGPointZero, inView: self.view) case .Ended: tileView.pop_addAnimation(createSpringAnimation(1), forKey: "springAnimation") if (invalid(tileView)) { UIView.animateWithDuration(0.5, animations: { () -> Void in tileView.center = self.startingPanPoint }) } else { if (contains(solutionTiles, tileView)) { solutionTiles.removeAtIndex(find(solutionTiles, tileView)!) } if (containedWithin(tileView, parent: solutionArea)) { var insertIndex = 0 for (index, tile) in enumerate(solutionTiles) { if (tileView.center.x < tile.center.x) { insertIndex = index } } solutionTiles.insert(tileView, atIndex: insertIndex) } adjustTiles(solutionTiles, area: solutionArea) } case .Failed, .Possible: UIView.animateWithDuration(1.0, animations: { () -> Void in tileView.center = self.startingPanPoint }) } } func adjustGoalTiles(tiles:[TileView], area:UIView) { let oldTileSide = tiles[0].frame.height let newTileSide = ceil(UIScreen.mainScreen().bounds.width * 0.9 / CGFloat(max(count(allowedChars),count(requiredChars))) - tileSpacing) let newTileSpacing = newTileSide * 0.25 let scale = newTileSide/oldTileSide for (var i=0; i<tiles.count; i++) { tiles[i].pop_addAnimation(createSpringAnimation(scale), forKey: "springAnimation") UIView.animateWithDuration(NSTimeInterval.abs(0.2), animations: { () -> Void in tiles[i].center.x = CGFloat(i)*(newTileSide+newTileSpacing) + newTileSide*0.5 + newTileSpacing tiles[i].center.y = area.frame.origin.y + area.frame.height/2 }) } } func adjustTiles(tiles:[TileView], area:UIView) { // let oldTileSide = tiles[0].frame.height // let newTileSide = ceil(UIScreen.mainScreen().bounds.width * 0.9 / CGFloat(tiles.count) - tileSpacing) // let newTileSpacing = newTileSide * 0.25 // let scale = newTileSide/oldTileSide // // shift tiles // for (var i=0; i<tiles.count; i++) { // tiles[i].pop_addAnimation(createSpringAnimation(scale), forKey: "springAnimation") // UIView.animateWithDuration(NSTimeInterval.abs(0.2), animations: { () -> Void in // tiles[i].center.x = CGFloat(i)*(newTileSide+newTileSpacing) + newTileSide + newTileSpacing // tiles[i].center.y = area.frame.origin.y + area.frame.height/2 // }) // } } func invalid(tile:TileView) -> Bool { if (tile.isRequired) { return containedWithin(tile, parent: allowedArea) || containedWithin(tile, parent: goalArea) } else { return containedWithin(tile, parent: goalArea) } } func containedWithin(child: UIView, parent:UIView) -> Bool { return CGRectIntersectsRect(child.frame, parent.frame) } func createSpringAnimation(scale: CGFloat) -> POPSpringAnimation { var springAnimation = POPSpringAnimation() springAnimation.property = POPAnimatableProperty.propertyWithName(kPOPViewScaleXY) as! POPAnimatableProperty springAnimation.springBounciness = 20.0 springAnimation.velocity = NSValue(CGPoint: CGPointMake(2,2)) springAnimation.toValue = NSValue(CGPoint: CGPointMake(scale, scale)) return springAnimation } @IBAction func back(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil ) } @IBAction func checkSolution(sender: AnyObject) { // check that all required tiles were used for tile in requiredTiles { if (!containedWithin(tile, parent: solutionArea)) { presentErrorModal("Try to include all required tiles!") return } } var solutionTiles:[TileView] = [] for tile in requiredTiles { if (containedWithin(tile, parent: solutionArea)) { solutionTiles.append(tile) } } for tile in allowedTiles { if (containedWithin(tile, parent: solutionArea)) { solutionTiles.append(tile) } } solutionTiles.sort { $0.0.frame.origin.x < $0.1.frame.origin.x } var solutionString:String = "" for tile in solutionTiles { solutionString.append(tile.letter) } let goalExpression = NSExpression(format: goalChars) let expression = NSExpression(format: solutionString) var result = expression.expressionValueWithObject(nil, context: nil) as! NSNumber var goal = goalExpression.expressionValueWithObject(nil, context: nil) as! NSNumber if (goal == result) { presentSuccessModal("Woohoo!") } else { presentErrorModal("Aw man :(") } } func presentSuccessModal(message: String) { let successVC = self.storyboard!.instantiateViewControllerWithIdentifier("successModal") as! UIViewController successVC.setPopinTransitionStyle(BKTPopinTransitionStyle.SpringySlide) successVC.setPopinTransitionDirection(BKTPopinTransitionDirection.Top) self.presentPopinController(successVC, fromRect: solutionArea.frame, animated: true, completion: nil) } func presentErrorModal(message: String) { let errorVC = self.storyboard!.instantiateViewControllerWithIdentifier("incorrectModal") as! IncorrectModalViewController errorVC.errorText = message errorVC.setPopinTransitionStyle(BKTPopinTransitionStyle.SpringySlide) errorVC.setPopinTransitionDirection(BKTPopinTransitionDirection.Top) self.presentPopinController(errorVC, fromRect: solutionArea.frame, animated: true, completion: nil) } @IBAction func resetBoard(sender: AnyObject) { renderBoard() } }
true
1fadae2fd4c2cf6bc58838f06cead243b26deb8e
Swift
Fytsyk/ViperSample
/IOSViperSample/IOSViperSample/base/BaseInteractor.swift
UTF-8
1,591
3.0625
3
[]
no_license
// // BaseInteractor.swift // TestTableView // // Created by Ivan Phytsyk on 9/23/18. // Copyright © 2018 Ivan Phytsyk. All rights reserved. // import Foundation class BaseInteractor<INPUT, OUTPUT> { private var input: INPUT? = nil private let executionQueue: DispatchQueue private let resultQueue: DispatchQueue private var onResult: ((OUTPUT?) -> Void)? private var onError: ((Error) -> Void)? private var workItem: DispatchWorkItem? init(executionQueue: DispatchQueue, resultQueue: DispatchQueue) { self.executionQueue = executionQueue self.resultQueue = resultQueue } func execute(_ input: INPUT?) throws -> OUTPUT? { fatalError("Need to be implemented in subclass") } func execute(input: INPUT? = nil, _ onResult: @escaping (OUTPUT?) -> Void, _ onError: @escaping (Error) -> Void) { self.input = input self.onResult = onResult self.onError = onError self.workItem = DispatchWorkItem {self.executeSafe()} executionQueue.async(execute: self.workItem!) } func cancel() { self.onResult = nil self.onError = nil self.workItem?.cancel() } private func executeSafe() { do { let result = try execute(input) runInResultQueue { self.onResult?(result) } } catch { runInResultQueue { self.onError?(error) } } } private func runInResultQueue(block: @escaping () -> Void) { resultQueue.async { block() } } }
true
92fa6d4a43b76d6ed490fb59fd6e31eb624cb718
Swift
its-me2000/StegoCube
/Nodes.swift
UTF-8
182
2.8125
3
[]
no_license
/* * Color cube nodes * * */ protocol Nodes { func addColor(_ color:Color)->Bool func getColorNodes()->[Nodes] func getColorNodeFor(color:Color)->ColorCube.ColorNode? }
true
f920b2f8e55c8b6343b123e3c88bc6c5fb41adb9
Swift
nahung89/GifTool
/GifTool/WatermarkView.swift
UTF-8
2,033
2.609375
3
[]
no_license
// // WatermarkView.swift // GifTool // // Created by Nah on 12/15/17. // Copyright © 2017 Nah. All rights reserved. // import Foundation import UIKit class WatermarkView: UIView { let label = UILabel() let imageView = UIImageView() struct Design { static let height: CGFloat = 48 static let font: UIFont = UIFont.FontHeavyBold(20) static let logoHeight: CGFloat = 32 static let padding: CGFloat = 8 } private let scale: CGFloat init(scale: CGFloat = 1) { self.scale = scale super.init(frame: CGRect(x: 0, y: 0, width: 0, height: Design.height * scale)) initView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initView() { let newPadding = Design.padding * scale imageView.image = #imageLiteral(resourceName: "VibbidiIcon") imageView.frame = CGRect(x: newPadding, y: 0, width: Design.logoHeight * scale, height: Design.logoHeight * scale) addSubview(imageView) imageView.layer.cornerRadius = newPadding imageView.layer.masksToBounds = true label.frame = CGRect(x: imageView.frame.maxX + newPadding, y: 0, width: 0, height: frame.height) label.textColor = .white label.text = "vibbidi.com" label.textAlignment = .right let designFont: UIFont = Design.font if scale == 1 { label.font = designFont } else { label.font = designFont.withSize(designFont.pointSize * scale) } label.sizeToFit() label.frame.size.height = frame.height addSubview(label) frame.size.width = label.frame.maxX + newPadding } override func layoutSubviews() { super.layoutSubviews() label.frame.origin.y = (frame.height - label.frame.height) / 2 imageView.frame.origin.y = (frame.height - imageView.frame.height) / 2 } }
true
3d2f0cc6ece29f3d2129843de15ffe22bff24463
Swift
adamgic/SpaceX
/SpaceX/Details/DetailsViewController.swift
UTF-8
2,577
2.6875
3
[]
no_license
// // DetailsViewController.swift // SpaceX // // Created by Recsio on 06/03/2018. // Copyright © 2018 Recsio. All rights reserved. // import UIKit import SafariServices import YouTubePlayer class DetailsViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var label: UILabel! @IBOutlet weak var videoView: YouTubePlayerView! @IBOutlet weak var stackView: UIStackView! var model: Launch? var image: UIImage? override func viewDidLoad() { super.viewDidLoad() configure() } func configure() { imageView.image = image if let model = model { var informations: [String] = [ "Rocket: \(model.rocket.rocketName)", "Location: \(model.launchSite)", model.details ?? "", "UTC Launch time: \(model.utcDateString)", "Local Launch time: \(model.localDateString)" ] if model.payloads.count > 0 { let payloadStrings = model.payloads.map { "\($0.payloadId) (\($0.payloadType))" } informations.append("Payload: \(payloadStrings.joined(separator: ", "))") } label.text = informations.joined(separator: "\n") if var links = model.links?.links { if let flightClub = model.flightClub { links.append(Link(name: "flight club", url: flightClub)) } links.forEach { link in guard let url = URL(string: link.url) else { return } let name = link.name.replacingOccurrences(of: "_", with: " ") let button = ButtonWithURL(type: .system) button.url = url button.setTitle(name, for: .normal) button.addTarget(self, action: #selector(buttonTouchUp), for: .touchUpInside) stackView.addArrangedSubview(button) } if let videoLink = links.first(where: { return $0.name == "video_link" && $0.url.contains("www.youtube.com") }), let url = URL(string: videoLink.url) { videoView.loadVideoURL(url) } } } } @objc func buttonTouchUp(_ sender: ButtonWithURL) { guard let url = sender.url else { return } present(SFSafariViewController(url: url), animated: true, completion: nil) } }
true
c2b5ca67fc920fa424245525edc4ca2b71b48a39
Swift
Mishgun31/ColorPaletteApp
/ColorPaletteApp/ViewControllers/SettingsViewController.swift
UTF-8
7,954
2.625
3
[]
no_license
// // SettingsViewController.swift // ColorPaletteApp // // Created by Михаил Мезенцев on 08.07.2021. // import UIKit class SettingsViewController: UIViewController { @IBOutlet weak var colorPaletteView: UIView! @IBOutlet weak var redValueLabel: UILabel! @IBOutlet weak var greenValueLabel: UILabel! @IBOutlet weak var blueValueLabel: UILabel! @IBOutlet weak var redSlider: UISlider! @IBOutlet weak var greenSlider: UISlider! @IBOutlet weak var blueSlider: UISlider! @IBOutlet weak var redTF: UITextField! @IBOutlet weak var greenTF: UITextField! @IBOutlet weak var blueTF: UITextField! @IBOutlet weak var scrollView: UIScrollView! var color: UIColor! var delegate: SettingsViewControllerDelegate! override func viewDidLoad() { super.viewDidLoad() redTF.delegate = self greenTF.delegate = self blueTF.delegate = self addGradientLayer() setColorPaletteAppearance() setValuesForSliders() setValuesForLabels() setValuesForTextFields() registerForKeboardNotifications() addTapGestureRecognizer() } @IBAction func sliderAction(_ sender: UISlider) { switch sender { case redSlider: redValueLabel.text = getValue(from: sender) redTF.text = getValue(from: sender) case greenSlider: greenValueLabel.text = getValue(from: sender) greenTF.text = getValue(from: sender) default: blueValueLabel.text = getValue(from: sender) blueTF.text = getValue(from: sender) } colorPaletteView.backgroundColor = setColor() color = setColor() } @IBAction func doneButtonPressed() { delegate.setColor(with: color) dismiss(animated: true) } } //MARK: - Private methods extension SettingsViewController { private func setColorPaletteAppearance() { colorPaletteView.layer.cornerRadius = 15 colorPaletteView.backgroundColor = color colorPaletteView.layer.borderWidth = 4 colorPaletteView.layer.borderColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) } private func setValuesForLabels() { redValueLabel.text = getValue(from: redSlider) greenValueLabel.text = getValue(from: greenSlider) blueValueLabel.text = getValue(from: blueSlider) } private func setValuesForSliders() { let color = CIColor(color: color) redSlider.value = Float(color.red) greenSlider.value = Float(color.green) blueSlider.value = Float(color.blue) } private func setValuesForTextFields() { redTF.text = getValue(from: redSlider) greenTF.text = getValue(from: greenSlider) blueTF.text = getValue(from: blueSlider) } private func getValue(from slider: UISlider) -> String { String(format: "%.2f", slider.value) } private func getFloatFrom(_ text: String) -> Float { let formattedText = text.replacingOccurrences(of: ",", with: ".") return Float(formattedText) ?? 1.0 } private func setColor() -> UIColor { UIColor( red: CGFloat(redSlider.value), green: CGFloat(greenSlider.value), blue: CGFloat(blueSlider.value), alpha: 1 ) } } //MARK: - UITextFieldDelegate extension SettingsViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { let toolBar = UIToolbar() textField.inputAccessoryView = toolBar toolBar.sizeToFit() let flexSpace = UIBarButtonItem( barButtonSystemItem: .flexibleSpace, target: nil, action: nil ) let doneButton = UIBarButtonItem( title: "Done", style: .done, target: self, action: #selector(endEditing) ) toolBar.items = [flexSpace, doneButton] } func textFieldDidEndEditing(_ textField: UITextField) { guard let text = textField.text else { return } switch textField { case redTF: let redValue = getFloatFrom(text) redSlider.setValue(redValue, animated: true) redValueLabel.text = getValue(from: redSlider) textField.text = getValue(from: redSlider) case greenTF: let greenValue = getFloatFrom(text) greenSlider.setValue(greenValue, animated: true) greenValueLabel.text = getValue(from: greenSlider) textField.text = getValue(from: greenSlider) default: let blueValue = getFloatFrom(text) blueSlider.setValue(blueValue, animated: true) blueValueLabel.text = getValue(from: blueSlider) textField.text = getValue(from: blueSlider) } colorPaletteView.backgroundColor = setColor() color = setColor() } } //MARK: - Working with keaboard extension SettingsViewController { @objc private func endEditing() { view.endEditing(true) } @objc private func keyboardWillShow(notification: Notification) { let keyboardInfo = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] guard let keyboardSize = (keyboardInfo as? NSValue)?.cgRectValue else { return } let contentInsets = UIEdgeInsets( top: 0, left: 0, bottom: keyboardSize.height + 5, right: 0 ) scrollView.contentInset = contentInsets scrollView.scrollIndicatorInsets = contentInsets } @objc private func keyboardWillHide(notification: Notification) { let contentInsets = UIEdgeInsets( top: 0, left: 0, bottom: 0, right: 0 ) scrollView.contentInset = contentInsets scrollView.scrollIndicatorInsets = contentInsets } private func registerForKeboardNotifications() { NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil ) } private func addTapGestureRecognizer() { let tapGestureRecognizer = UITapGestureRecognizer( target: self, action: #selector(endEditing) ) view.addGestureRecognizer(tapGestureRecognizer) } } //MARK: - Set gradient extension SettingsViewController { private func addGradientLayer() { let colorOne = UIColor( red: 14 / 255, green: 217 / 255, blue: 120 / 255, alpha: 1 ) let colorTwo = UIColor( red: 10 / 255, green: 128 / 255, blue: 71 / 255, alpha: 1 ) let colorThree = UIColor( red: 3 / 255, green: 45 / 255, blue: 25 / 255, alpha: 1 ) let gradient = CAGradientLayer() gradient.frame = view.bounds gradient.colors = [ colorOne.cgColor, colorTwo.cgColor, colorThree.cgColor ] view.layer.insertSublayer(gradient, at: 0) // gradient.locations = [0.0, 1.0] // gradient.startPoint = CGPoint(x: 0, y: 0) // gradient.endPoint = CGPoint(x: 0, y: 1) } }
true
289912e4ea5f3644957a563237d6af2af900f01e
Swift
FitDogTracker/FitDog
/FitDog/ViewControllers/SelectDogViewController.swift
UTF-8
3,919
2.578125
3
[]
no_license
// // SelectDogViewController.swift // FitDog // // Created by Coleman on 3/26/18. // Copyright © 2018 Kristine Laranjo. All rights reserved. // import UIKit import Parse class SelectDogViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var goButton: UIButton! @IBOutlet weak var tableView: UITableView! var dogs: [Dog]! var selectedDogs: [SelectDogCell] = [] var currentDogs: [Dog] = [] override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.font: UIFont(name: "ChalkboardSE-Bold", size: 25)!, NSAttributedStringKey.foregroundColor: UIColor.white] self.navigationController?.navigationBar.barTintColor = UIColor(hexString: "#b22222ff") self.view.backgroundColor = UIColor(hexString: "#fffaf0ff") tableView.backgroundColor = UIColor(hexString: "#fffaf0ff") goButton.backgroundColor = UIColor(hexString: "#fffaf0ff") goButton.layer.borderWidth = 2 goButton.layer.masksToBounds = false goButton.layer.borderColor = UIColor(hexString: "#4d2600ff")?.cgColor goButton.layer.cornerRadius = goButton.frame.height/2 goButton.clipsToBounds = true // Do any additional setup after loading the view. tableView.delegate = self tableView.dataSource = self } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SelectDogCell", for: indexPath) as! SelectDogCell cell.dog = dogs[indexPath.row] cell.backgroundColor = UIColor(hexString: "#fffaf0ff") return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! SelectDogCell isValid() if cell.isSelected { selectedDogs.append(cell) currentDogs.append(dogs[indexPath.row]) } isValid() } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! SelectDogCell var index = 0 isValid() if cell.isSelected == false { for dog in selectedDogs { if selectedDogs.contains(dog) { selectedDogs.remove(at: index) currentDogs.remove(at: index) isValid() return } index = index + 1 } } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dogs.count } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func didTapGo(_ sender: Any) { if (selectedDogs.count > 0) { let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let destination = storyBoard.instantiateViewController(withIdentifier: "CurrentWalkViewController") as! CurrentWalkViewController destination.dogs = selectedDogs destination.currentDogs = currentDogs self.present(destination, animated:true, completion:nil) } else { print("No dogs selected") } } func isValid() { if (selectedDogs.count == 0) { goButton.backgroundColor = UIColor(hexString: "#fffaf0ff") goButton.setTitleColor(UIColor(hexString: "#4d2600ff"), for: .normal) } else { goButton.backgroundColor = UIColor(hexString: "#b22222ff") goButton.setTitleColor(UIColor.white, for: .normal) } } }
true
4582a8c252ac2fa7baefbbc501dec51b74138318
Swift
CodeKul/Blancco-Swift-iOS-Corporate-May-2020
/iOSDemos/UserDefaultsDemo/UserDefaultsDemo/ViewController.swift
UTF-8
1,438
2.65625
3
[]
no_license
// // ViewController.swift // UserDefaultsDemo // // Created by Apple on 15/05/20. // Copyright © 2020 Codekul. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var userTxt: UITextField! @IBOutlet var passTxt: UITextField! @IBOutlet var isLoggedinSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() let username = UserDefaults.standard.value(forKey: "username") as? String let password = UserDefaults.standard.value(forKey: "password") as? String if username == "user" && password == "pass" { let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "HomeViewController") self.navigationController?.pushViewController(vc, animated: false) } } @IBAction func loginButtonCLick(_ sender: UIButton) { if userTxt.text == "user" && passTxt.text == "pass" { if isLoggedinSwitch.isOn { UserDefaults.standard.set(userTxt.text, forKey: "username") UserDefaults.standard.set(passTxt.text, forKey: "password") UserDefaults.standard.synchronize() } let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "HomeViewController") self.navigationController?.pushViewController(vc, animated: true) } } }
true
5029163bcb3061c1bf1b28fd16cf245a5f584dc1
Swift
yummy1/swift_Community
/swift_Community/Main(主要功能模块)/Discount/View/DiscountHeaderView.swift
UTF-8
3,670
2.59375
3
[]
no_license
// // DiscountHeaderView.swift // swift_Community // // Created by MM on 2018/11/7. // Copyright © 2018年 MM. All rights reserved. // import Foundation import UIKit protocol DiscountHeaderViewProtocol:NSObjectProtocol { func clickCallBack(tag:Int) } class DiscountHeaderView: UIView { var categoryBtn:UIButton? var latestBtn:UIButton? var nearestBtn:UIButton? weak var delegate:DiscountHeaderViewProtocol? override init(frame: CGRect) { super.init(frame: frame) self.setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI() { self.backgroundColor = UIColor.groupTableViewBackground self.categoryBtn = UIButton.init() self.categoryBtn?.tag = 0 self.categoryBtn?.setTitle("All Category", for: .normal) self.categoryBtn?.setTitleColor(ThemeColor, for: .normal) self.categoryBtn?.setBackgroundImage(UIImage.from(color: .white), for: .normal) self.categoryBtn?.addTarget(self, action: #selector(clickAction(button:)), for: .touchUpInside) self.addSubview(self.categoryBtn!) self.latestBtn = UIButton.init() self.latestBtn?.tag = 1 self.latestBtn?.setTitle("Latest", for: .normal) self.latestBtn?.setTitleColor(.black, for: .normal) self.latestBtn?.setTitleColor(ThemeColor, for: .selected) self.latestBtn?.setBackgroundImage(UIImage.from(color: .white), for: .normal) self.latestBtn?.addTarget(self, action: #selector(clickAction(button:)), for: .touchUpInside) self.addSubview(self.latestBtn!) self.nearestBtn = UIButton.init() self.nearestBtn?.tag = 2; self.nearestBtn?.setTitle("Nearest", for: .normal) self.nearestBtn?.setTitleColor(.black, for: .normal) self.nearestBtn?.setTitleColor(ThemeColor, for: .selected) self.nearestBtn?.setBackgroundImage(UIImage.from(color: .white), for: .normal) self.nearestBtn?.addTarget(self, action: #selector(clickAction(button:)), for: .touchUpInside) self.addSubview(self.nearestBtn!) } @objc func clickAction(button:UIButton){ if (button.tag != 0){ button.isSelected = !button.isSelected if (button.tag == 1){ self.nearestBtn?.isSelected = false }else{ self.latestBtn?.isSelected = false } if (!button.isSelected){ delegate?.clickCallBack(tag: 4) }else{ delegate?.clickCallBack(tag: button.tag) } }else{ delegate?.clickCallBack(tag: button.tag) } } override func layoutSubviews() { super.layoutSubviews() self.categoryBtn?.snp.makeConstraints({ (make) in make.left.top.equalTo(self) make.width.equalTo(ScreenWidth*0.4) make.bottom.equalTo(self).offset(-1) }) self.latestBtn?.snp.makeConstraints({ (make) in make.top.equalTo(self) make.bottom.equalTo(self).offset(-1) make.left.equalTo((self.categoryBtn?.snp_rightMargin)!) make.width.equalTo(ScreenWidth*0.3) }) self.nearestBtn?.snp.makeConstraints({ (make) in make.right.top.equalTo(self) make.bottom.equalTo(self).offset(-1) make.left.equalTo((self.latestBtn?.snp_rightMargin)!) }) } } extension UIButton{ override open var isHighlighted: Bool { set{ } get { return false } } }
true
dcd9b60ab8613de4002dd29c7bc20184e94f2ea3
Swift
kasimok/SimpleTunnel
/mac/ViewController.swift
UTF-8
4,304
2.546875
3
[]
no_license
// // ViewController.swift // mac // // Created by 孔祥波 on 05/01/2018. // Copyright © 2018 Apple Inc. All rights reserved. // import Cocoa import NetworkExtension class ViewController: NSViewController { var manager:NETunnelProviderManager? override func viewDidLoad() { super.viewDidLoad() loadManager() // Do any additional setup after loading the view. } @IBAction func save(_ sender: Any) { guard self.manager != nil else { fatalError() } } func loadManager(){ NETunnelProviderManager.loadAllFromPreferences { (ms, e) in print(ms as Any) if let ms = ms{ if ms.count != 0 { for m in ms { self.manager = m } }else { self.create() } } } } @IBAction func dail(_ sender: Any) { _ = try! startStopToggled("") } func create(){ let config = NETunnelProviderProtocol() //config.providerConfiguration = ["App": bId,"PluginType":"com.yarshure.Surf"] #if os(iOS) config.providerBundleIdentifier = "com.yarshure.Surf.PacketTunnel" #else config.providerBundleIdentifier = "com.yarshure.Surf.mac.extension" #endif config.serverAddress = "192.168.11.9:8890" let manager = NETunnelProviderManager() manager.protocolConfiguration = config manager.localizedDescription = "Surfing" manager.saveToPreferences(completionHandler: { (error) -> Void in if error != nil { print(error?.localizedDescription as Any) }else { self.manager = manager } }) } func startStopToggled(_ config:String) throws ->Bool{ if let m = manager { if m.connection.status == .disconnected || m.connection.status == .invalid { do { if m.isEnabled { try m.connection.startVPNTunnel(options: [:]) }else { } } catch let error { throw error //mylog("Failed to start the VPN: \(error)") } } else { print("stoping!!!") m.connection.stopVPNTunnel() } }else { return false } return true } @IBAction func XPC(_ sender: Any) { // Send a simple IPC message to the provider, handle the response. //AxLogger.log("send Hello Provider") if let m = manager { let me = "|Hello Provider" if let session = m.connection as? NETunnelProviderSession, let message = me.data(using: .utf8), m.connection.status != .invalid { do { try session.sendProviderMessage(message) { response in if let response = response { if let responseString = String.init(data:response , encoding: .utf8){ _ = responseString.components(separatedBy: ":") print("Received response from the provider: \(responseString)") } //self.registerStatus() } else { print("Got a nil response from the provider") } } } catch { print("Failed to send a message to the provider") } } }else { print("message dont init") } } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } }
true
60a53002c24c7cf4d97c67620edc3ff24bb0111f
Swift
Dongxi729/MJMarket
/MJMarket/utils/Category/UnderLineLabel.swift
UTF-8
816
3.09375
3
[]
no_license
// // UnderLineLabel.swift // MJMarket // // Created by 郑东喜 on 2017/8/28. // Copyright © 2017年 郑东喜. All rights reserved. // import UIKit // 带下划线的label import UIKit // MARK: - https://stackoverflow.com/questions/28053334/how-to-underline-a-uilabel-in-swift class UnderLineLabel : UILabel { override var text: String? { didSet { guard let text = text else { return } let textRange = NSMakeRange(0, text.characters.count) let attributedText = NSMutableAttributedString(string: text) attributedText.addAttribute(NSUnderlineStyleAttributeName , value: NSUnderlineStyle.styleSingle.rawValue, range: textRange) // Add other attributes if needed self.attributedText = attributedText } } }
true
c7dbcdd4a9d4e58cba3b04ab66eff325d72a5d75
Swift
Frostjaw/ios_lab2
/ios_lab2/CustomFiles/TextFieldWithBottomBorder.swift
UTF-8
1,117
2.75
3
[]
no_license
// // TextFieldWithBottomBorder.swift // ios_lab2 // // Created by Frostjaw on 13/04/2020. // Copyright © 2020 Frostjaw. All rights reserved. // import UIKit class TextFieldWithBottomBorder: UITextField { override init(frame: CGRect) { super.init(frame: frame) setupTextField() } required init?(coder: NSCoder) { super.init(coder: coder) setupTextField() } private func setupTextField(){ self.translatesAutoresizingMaskIntoConstraints = false let bottomBorder = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) bottomBorder.backgroundColor = UIColor(red: 60/255, green: 60/255, blue: 67/255, alpha: 0.29) bottomBorder.translatesAutoresizingMaskIntoConstraints = false self.addSubview(bottomBorder) bottomBorder.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true bottomBorder.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true bottomBorder.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true bottomBorder.heightAnchor.constraint(equalToConstant: 1).isActive = true } }
true
e30f81f75e37d6c821f67ca48a132a71149d4b75
Swift
snigdhaman/Prime-Checker
/Prime Checker/ViewController.swift
UTF-8
1,413
3.15625
3
[]
no_license
// // ViewController.swift // Prime Checker // // Created by Chatterjee, Snigdhaman on 20/12/15. // Copyright © 2015 Chatterjee, Snigdhaman. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var inputTextField: UITextField! @IBOutlet weak var outputLabel: UILabel! @IBAction func checkButton(sender: AnyObject) { if let inputNumber = Int(inputTextField.text!) { let isPrime = checkForPrime(inputNumber) if isPrime { outputLabel.text = "Number \(inputNumber) is Prime!!!" } else { outputLabel.text = "Number \(inputNumber) is not Prime." } } else { outputLabel.text = "Please enter a number" } } func checkForPrime(num:Int) -> Bool { if num == 1 || num == 0 { return false } for var i = 2; i <= (num/2); i++ { if num%i == 0 { return false } } return true } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
c0e64fa491e1e3a31298f95ab6627bbbf70b8b8a
Swift
leandrowauters/Mano-ride-sharing-app
/Mano/app-ui/AlertViewController.swift
UTF-8
1,129
2.734375
3
[]
no_license
// // AlertViewController.swift // Mano // // Created by Leandro Wauters on 9/3/19. // Copyright © 2019 Leandro Wauters. All rights reserved. // import UIKit protocol AlertViewDelegate: AnyObject { func okayPressed() } class AlertViewController: UIViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var messageLabel: UILabel! let titleMessage: String! let message: String? weak var delegate: AlertViewDelegate? override func viewDidLoad() { super.viewDidLoad() if let message = message { messageLabel.text = message } titleLabel.text = titleMessage } init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, title: String, message: String?) { self.titleMessage = title self.message = message super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBAction func okayPressed(_ sender: Any) { dismiss(animated: true) delegate?.okayPressed() } }
true
414c5ecbccbf388e1060c38117042b5d895f602a
Swift
ngominhtrint/GoogleMapDirectionLib
/GoogleMapDirectionLib/Model/Agency.swift
UTF-8
541
2.6875
3
[ "Apache-2.0" ]
permissive
// // Agency.swift // GoogleMapDirectionLib // // Created by TriNgo on 5/12/20. // Copyright © 2020 RoverDream. All rights reserved. // import Foundation import ObjectMapper public struct Agency: Mappable { public private(set) var name: String? public private(set) var url: String? public init?(map: Map) { } init() { } public mutating func mapping(map: Map) { name <- map[AgencyKey.name] url <- map[AgencyKey.url] } } fileprivate struct AgencyKey { static let name = "name" static let url = "url" }
true
02d744fff17914fdcb93fb3e9407d244fc91af1e
Swift
apferrarone/go-chat-ios
/GoChat/TeamNavBar.swift
UTF-8
4,156
2.640625
3
[]
no_license
// // TeamNavBar.swift // GoChat // // Created by Andrew Ferrarone on 12/12/16. // Copyright © 2016 Andrew Ferrarone. All rights reserved. // import UIKit enum NavBarSide { case left case right } // if you subclass UINavigationBar, the nav controller must be initialized with init(navigationBarClass:toolbarClass:) class TeamNavBar: UINavigationBar { let DARK_GRAY = UIColor(hex: Constants.ColorHexValues.DARK_GRAY) // returns the UISwtich from the topLevel Navigation Item // so the visible Nav Bar switch, checking for it on the left side first var topTeamSwitch: UISwitch? { get { if let button = self.topItem?.leftBarButtonItem?.customView as? UISwitch { return button } else if let button = self.topItem?.rightBarButtonItem?.customView as? UISwitch { return button } return nil } } var allTeamSwitches: [UISwitch] { get { var switches = [UISwitch]() if let items = self.items { for item in items { if let button = self.switchFromItem(item) { switches.append(button) } } } return switches } } required override init(frame: CGRect) { super.init(frame: frame) self.setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } func setup() { self.barTintColor = DARK_GRAY self.updateBasedOnTeamColor() self.listenForColorChanges(true) } deinit { self.listenForColorChanges(false) } // Utilities fileprivate func switchFromItem(_ item: UINavigationItem) -> UISwitch? { var buttonSwitch = item.leftBarButtonItem?.customView as? UISwitch if buttonSwitch == nil { buttonSwitch = item.rightBarButtonItem?.customView as? UISwitch } return buttonSwitch } fileprivate func listenForColorChanges(_ shouldListen: Bool) { if shouldListen { NotificationCenter.default.addObserver(self, selector: #selector(colorsChanged), name: Notification.Name(rawValue: Constants.Notifications.NOTIFICATION_TEAM_CHANGE), object: nil) } else { NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: Constants.Notifications.NOTIFICATION_TEAM_CHANGE), object: nil) } } func colorsChanged(notification: Notification) { self.updateBasedOnTeamColor() } fileprivate func updateBasedOnTeamColor() { self.isTranslucent = false self.isOpaque = true if let user = User.currentUser() { let color = user.currentColor() let otherColor = color == DARK_GRAY ? user.team?.color : DARK_GRAY self.barTintColor = color UIView.animate(withDuration: 0.23) { for button in self.allTeamSwitches { button.isOn = user.teamMode == .team button.tintColor = self.DARK_GRAY button.onTintColor = otherColor button.backgroundColor = otherColor button.layer.cornerRadius = 16 } } } #if DEBUG for button in self.allTeamSwitches { button.onTintColor = UIColor(hex: Constants.ColorHexValues.CRYPTO_PINK) } #endif } } /** * Extension UINavBar */ extension UINavigationItem { func showSpinner(onSide side: NavBarSide) { let spinner = UIActivityIndicatorView(activityIndicatorStyle: .white) spinner.hidesWhenStopped = true spinner.startAnimating() let barButtonSpinner = UIBarButtonItem(customView: spinner) switch side { case .right: self.rightBarButtonItem = barButtonSpinner case .left: self.leftBarButtonItem = barButtonSpinner } } }
true
5eccff2dab61b3c4464761ed1554d723b22598b8
Swift
cnluocj/diancaila
/diancaila/DeskPickerViewController.swift
UTF-8
3,747
2.734375
3
[]
no_license
// // DeskPickerViewController.swift // diancailaUIdemo // // Created by 罗楚健 on 14/11/20. // Copyright (c) 2014年 diancaila. All rights reserved. // import UIKit protocol OrderValuePassDelegate { func value(value: Any) } class DeskPickerViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { var delegate: OrderValuePassDelegate! var picker :UIPickerView! var deskId: Int = 1 var numOfDesk: Int = 10 override func viewDidLoad() { super.viewDidLoad() self.title = "选择桌子" self.view.backgroundColor = UIUtil.gray_system let navBar = UINavigationBar(frame: CGRectMake(0, 0, UIUtil.screenWidth, 44 + UIUtil.statusHeight)) navBar.backgroundColor = UIUtil.navColor //22为iphone状态栏高度 let navImage = UIUtil.imageFromColor(UIUtil.screenWidth, height: 44 + UIUtil.statusHeight, color: UIUtil.navColor) // 改变背景颜色,使用生成的纯色图片 navBar.setBackgroundImage(navImage, forBarMetrics: UIBarMetrics.Default) // 主体是否从顶部开始 navBar.translucent = false // 改变title颜色 navBar.titleTextAttributes = NSDictionary(object: UIColor.whiteColor(), forKey: NSForegroundColorAttributeName) // 改变导航栏上字体颜色,除了title navBar.tintColor = UIColor.whiteColor() let navitem = UINavigationItem(title: "选择桌子") let cancelButton = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Bordered, target: self, action: "didPressCancelButton:") let doneButton = UIBarButtonItem(title: "确定", style: UIBarButtonItemStyle.Bordered, target: self, action: "didPressDoneButton:") navitem.setLeftBarButtonItem(cancelButton, animated: false) navitem.setRightBarButtonItem(doneButton, animated: false) navBar.pushNavigationItem(navitem, animated: false) self.view.addSubview(navBar) self.picker = UIPickerView(frame: CGRectMake(0, 120, UIUtil.screenWidth, 150)) self.picker.backgroundColor = UIColor.whiteColor() self.picker.delegate = self self.picker.dataSource = self self.view.addSubview(picker) } func didPressCancelButton(sender: UIBarButtonItem) { self.dismissViewControllerAnimated(true, completion: nil) } func didPressDoneButton(sender: UIBarButtonItem) { self.delegate.value(deskId) self.dismissViewControllerAnimated(true, completion: nil) } // about picker func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return numOfDesk } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { return "第\(row+1)桌" } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { deskId = row+1 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
96f922678bc490080ba53be76dd4b962d8ba1399
Swift
Legoless/iOS-Course
/2015-1/Lesson15/MyWeather/MyWeather/WeatherLoadOperation.swift
UTF-8
2,640
2.984375
3
[ "MIT" ]
permissive
// // WeatherLoadOperation.swift // MyWeather // // Created by Dal Rupnik on 29/11/15. // Copyright © 2015 Unified Sense. All rights reserved. // import Foundation let APIKey = "" class WeatherLoadOperation: NSOperation { var location = "" // Called when completed with parsed temperature as double, parsed weather icon and any object JSON var completionHandler : ((Double, WeatherIcon, AnyObject) -> Void)? override func main () -> Void { let request = NSMutableURLRequest() request.URL = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?units=metric&appid=" + APIKey + "&q=" + location.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet())!)! request.HTTPMethod = "GET" let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in if error != nil || data == nil { return } do { let JSON = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as! [String : AnyObject] let weather = JSON["main"]! let description = JSON["weather"]![0]["description"] as! String var icon : WeatherIcon = .Sunny if description.containsString("cloud") { icon = .Cloudy } else if description.containsString("fog") { icon = .Fog } else if description.containsString("drizzle") { icon = .Showers } else if description.containsString("rain") { icon = .Rain } else if description.containsString("snow") { icon = .Sunny } else if description.containsString("thunder") { icon = .Thunder } let temperature = weather as! [String : AnyObject] if let temp = temperature["temp"] as? NSNumber { if let completionHandler = self.completionHandler { completionHandler(temp.doubleValue, icon, weather) } } } catch { } } task.resume() } }
true
fb4ba2998d55ae470075e7df3626eee1848e4a75
Swift
jeffChavez/JCKit
/JCKit/Extensions/Double.swift
UTF-8
105
2.921875
3
[ "MIT" ]
permissive
import Foundation extension Double { public var asFloat: Float { return Float(self) } }
true
9b88a2b6ceaddeb5b9f44f10039288f43da22a67
Swift
bekadeveloper/leetcode
/minimum-operations-to-make-the-array-increasing/minimum-operations-to-make-the-array-increasing.swift
UTF-8
321
2.75
3
[ "MIT" ]
permissive
class Solution { func minOperations(_ nums: [Int]) -> Int { var nums = nums, result = 0 for i in 0..<nums.count-1 where nums[i] >= nums[i+1] { let amount = nums[i] - nums[i+1] + 1 nums[i+1] += amount result += amount } return result } }
true
a3c8a310cc6d8df0b75bac76378427029a784eeb
Swift
JaMata/Flips
/Views/ProfileView.swift
UTF-8
1,451
2.984375
3
[ "Unlicense" ]
permissive
// // ProfileView.swift // Flips // // Created by Jordan Foster on 3/30/21. // import SwiftUI struct ProfileView: View { var user: UserEntity var body: some View { let myFlips = Array(user.flips as! Set<FlipEntity>) VStack { AsyncImage( url: user.profileImage!, placeholder: { Text("...") }, image: { Image(uiImage: $0).resizable() } ) .aspectRatio(contentMode: .fit) .clipShape(Circle()) .frame(width: 175, height: 175) Text("\(user.username!)") .font(.largeTitle) Text("\(user.bio ?? "")") .font(.headline) Spacer() Form { HStack { Text("Name:") Spacer() Text(user.name!) } HStack { Text("Email:") Spacer() Text(user.email!) } HStack { Text("Location:") Spacer() Text("\(user.city ?? ""), \(user.state ?? "")") } } Spacer() Text("Flips") .font(.title) ScrollView(.horizontal) { HStack { ForEach(myFlips, id: \.self) { flip in AsyncImage( url: flip.image!, placeholder: { Text("...") }, image: { Image(uiImage: $0).resizable() } ) .aspectRatio(contentMode: .fit) .frame(width: 100, height: 100) .clipShape(Rectangle()) } } } Spacer() } } } struct ProfileView_Previews: PreviewProvider { static var previews: some View { ProfileView(user: FlipsDataModel.designModel.users.first!.convertToManagedObject()) } }
true
9de6b47033bf126a602e311e8216d28fc0556185
Swift
DeveloperFly/AGCommonCodeSwift
/AGCommonCodeSwift/Classes/AGStringExtension/AGStringExtended.swift
UTF-8
4,096
3.171875
3
[ "MIT" ]
permissive
// // AGStringExtended.swift // AGCommonCodeSwift // // Created by Aman Gupta on 26/12/17. // import UIKit public extension String { // MARK: - Public variables public var first: String { return String(prefix(1)) } public var last: String { return String(suffix(1)) } public var uppercaseFirstChar: String { return first.uppercased() + String(dropFirst()) } public var vowels: [String] { get { return ["a", "e", "i", "o", "u"] } } public var consonants: [String] { get { return ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "z"] } } public var length: Int { get { return self.stringByTrimmingWhiteSpaceAndNewLine().count } } //To check whether email is valid or not public func isEmail() -> Bool { if self.isEmptyString() { return false } let emailRegex = "[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}" as String let emailText = NSPredicate(format: "SELF MATCHES %@",emailRegex) let isValid = emailText.evaluate(with: self) as Bool return isValid } //To check whether URL is valid public func isURL() -> Bool { let urlRegex = "(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+" as String let urlText = NSPredicate(format: "SELF MATCHES %@", urlRegex) let isValid = urlText.evaluate(with: self) as Bool return isValid } //To check whether image URL is valid public func isImageURL() -> Bool { if self.isURL() { if self.range(of: ".png") != nil || self.range(of: ".jpg") != nil || self.range(of: ".jpeg") != nil { return true } else { return false } } else { return false } } //To check whether string is empty public func isEmptyString() -> Bool { return self.stringByTrimmingWhiteSpace().count == 0 ? true : false } //Get string by removing white space public func stringByTrimmingWhiteSpace() -> String { return self.trimmingCharacters(in: .whitespaces) } //Get string by removing white space & new line public func stringByTrimmingWhiteSpaceAndNewLine() -> String { return self.trimmingCharacters(in: .whitespacesAndNewlines) } //Remove substring in string mutating public func removeSubString(subString: String) -> String { if self.contains(subString) { guard let stringRange = self.range(of: subString) else { return self } return self.replacingCharacters(in: stringRange, with: "") } return self } public static func getString(message: Any?) -> String { guard let strMessage = message as? String else { guard let doubleValue = message as? Double else { guard let intValue = message as? Int else { guard let int64Value = message as? Int64 else { return "" } return String(int64Value) } return String(intValue) } let formatter = NumberFormatter() formatter.minimumFractionDigits = 0 formatter.maximumFractionDigits = 2 formatter.minimumIntegerDigits = 1 guard let formattedNumber = formatter.string(from: NSNumber(value: doubleValue)) else { return "" } return formattedNumber } return strMessage.stringByTrimmingWhiteSpaceAndNewLine() } public func replace(target: String, withString: String) -> String { return self.replacingOccurrences(of: target, with: withString) } //Get character array by string public func getArrayByString() -> [Character] { return Array(self) } }
true
ef710c7ac9253d04636c25e3a12904587b9d48d1
Swift
dangquockhanh/API
/DemoAlamofireImage/DemoAlamofireImage/ViewController.swift
UTF-8
833
2.578125
3
[]
no_license
// // ViewController.swift // DemoAlamofireImage // // Created by Đặng Khánh on 9/11/19. // Copyright © 2019 DangKhanh. All rights reserved. // import UIKit import Alamofire import AlamofireImage class ViewController: UIViewController { @IBOutlet weak var photoImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() Alamofire.request("https://hinhanhdep.org/wp-content/uploads/2016/08/songoku-super-saiyan-cap-3.png").responseImage { response in debugPrint(response) debugPrint(response.result) if let image = response.result.value { // print("image downloaded: \(image)") DispatchQueue.main.async { self.photoImageView.image = image } } } } }
true
4195d86d13ae9d43df9ba8efeb3b726be14e9fd9
Swift
ChoadPet/News
/WorldwideNews/Business Logic/Services/NetworkManager/RequestManager/RequestManager.swift
UTF-8
2,247
2.921875
3
[]
no_license
// // NetworkManager.swift // NetworkManager // // Created by Vetaliy Poltavets on 12/7/19. // Copyright © 2019 vpoltave. All rights reserved. // import Foundation typealias CompletionHandler = ((Result<CustomResponse, Error>) -> Void) protocol RequestManagerProvider { associatedtype Api: ApiProvider func request(api: Api, completion: @escaping (Result<CustomResponse, Error>) -> Void) } final class RequestManager<Api: ApiProvider> { private let session: DataTaskCreator init(session: DataTaskCreator = URLSession.shared) { self.session = session } // MARK: - Private API @discardableResult private func createDataTask(with request: URLRequest, completion: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask { return session.dataTask(with: request, completionHandler: completion) } // TODO: Can be improve ... private func createURLRequest(forAPI api: Api) -> URLRequest { var components = URLComponents(url: URL(api: api), resolvingAgainstBaseURL: false)! components.queryItems = api.parameters.map { URLQueryItem(name: $0, value: "\($1)") } var request = URLRequest(url: components.url!) request.httpMethod = api.method.rawValue for (headerField, value) in api.headers { request.setValue(value, forHTTPHeaderField: headerField) } return request } } extension RequestManager: RequestManagerProvider { func request(api: Api, completion: @escaping CompletionHandler) { let urlRequest = createURLRequest(forAPI: api) createDataTask(with: urlRequest) { data, response, error in guard let data = data, let response = response as? HTTPURLResponse, error == nil else { return completion(.failure(error!)) } let customResponse = CustomResponse(statusCode: response.statusCode, data: data, response: response) completion(.success(customResponse)) }.resume() } } private extension URL { init(api: ApiProvider) { self = api.baseURL.appendingPathComponent(api.path) } }
true
f6cf5ca65f36a84b1e5cdbd94e924dfbbbd179b7
Swift
kagaffy/Othello-Game
/othello/Models/AuxiliaryModels.swift
UTF-8
768
3.359375
3
[]
no_license
// // AuxiliaryModels.swift // othello // // Created by 塚田良輝 on 2019/01/09. // Copyright © 2019年 塚田良輝. All rights reserved. // import Foundation enum StoneObject { case empty case black case white } struct SquareMatrix<T> { let dimention: Int var boardArray: [T] init(dimention d: Int, initialValue: T) { dimention = d boardArray = [T](repeating: initialValue, count: d*d) } subscript(row: Int, col: Int) -> T { get { assert(row >= 0 && row < dimention) assert(col >= 0 && col < dimention) return boardArray[row*dimention + col] } set { assert(row >= 0 && row < dimention) assert(col >= 0 && col < dimention) boardArray[row*dimention + col] = newValue } } }
true
e1832a5236b7e5ce33d2af7d86d776f210137421
Swift
rezakhmf/flight-timetable
/Qantas/AirportModelExt.swift
UTF-8
2,265
2.734375
3
[]
no_license
// // AirportModelExt.swift // Qantas // // Created by Reza Farahani on 14/3/17. // Copyright © 2017 Reza Farahani. All rights reserved. // import Foundation extension Airport{ init?(json:[String:Any]) throws { guard let code = json["code"] as? String else { throw SerializationAirportError.missing("code") } guard let displayName = json["display_name"] as? String else { throw SerializationAirportError.missing("display_name") } guard let internationalAirport = json["international_airport"] as? Bool else { throw SerializationAirportError.missing("international_airport") } guard let regionalAirport = json["regional_airport"] as? Bool else { throw SerializationAirportError.missing("regional_airport") } guard let locationJson = json["location"] as? [String:Double] , let latitude = locationJson["latitude"], let longitude = locationJson["latitude"] else { throw SerializationAirportError.missing("location") } //check not random geolocation let location = (latitude, longitude) guard case(-90...90, -180...180) = location else { throw SerializationAirportError.invalid("location", location) } guard let currencyCode = json["currency_code"] as? String else { throw SerializationAirportError.missing("currency_code") } guard let timeZone = json["timezone"] as? String else { throw SerializationAirportError.missing("timezone") } guard let country = json["country"] as? [String:String], let countryCode = country["countryCode"], let countryName = country["countryName"] else { throw SerializationAirportError.missing("country") } // Initialize airport properties self.code = code self.displayName = displayName self.internationalAirport = internationalAirport self.regionalAirport = regionalAirport self.location = (latitude, longitude) self.currencyCode = currencyCode self.timeZone = timeZone self.country = (countryCode, countryName) } }
true
8b0c1e01782ec5ff7125e28c0b2e75ec718bf723
Swift
hellyeah/BitClout
/Blockchain/DataModel/Metadata/LikeMetadata.swift
UTF-8
316
2.5625
3
[ "MIT" ]
permissive
// // LikeMetadata.swift // BitClout // // Created by Ludovic Landry on 3/20/21. // import Foundation struct LikeMetadata: Codable { enum CodingKeys: String, CodingKey { case isUnlike = "IsUnlike" case postHashHex = "PostHashHex" } let isUnlike: Bool let postHashHex: String }
true
efecb398815dd62c07e70e0767e033a66160993f
Swift
sondresallaup/SnapMail
/MailSnap/SignUpZipViewController.swift
UTF-8
2,741
2.71875
3
[]
no_license
// // SignUpZipViewController.swift // MailSnap // // Created by Sondre Sallaup on 25/09/15. // Copyright © 2015 Sondre Sallaup. All rights reserved. // import UIKit class SignUpZipViewController: UIViewController, UITextFieldDelegate, NSXMLParserDelegate { @IBOutlet weak var zipNumberInput: UITextField! @IBOutlet weak var createAccountButton: UIBarButtonItem! @IBOutlet weak var postalAreaLabel: UILabel! var fullName: String! var email: String! var streetAddress: String! override func viewDidLoad() { super.viewDidLoad() zipNumberInput.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged) zipNumberInput.becomeFirstResponder() zipNumberInput.delegate = self } func textFieldDidChange(textField: UITextField) { if(zipNumberInput.text?.characters.count == 4) { getPostalArea() } else { createAccountButton.enabled = false postalAreaLabel.enabled = false } } func textFieldShouldReturn(textField: UITextField) -> Bool { if(zipNumberInput.text?.characters.count == 4) { self.performSegueWithIdentifier("zipToUsername", sender: self) return true } else { return false } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "zipToUsername") { if let viewController: SignUpUsernameViewController = segue.destinationViewController as? SignUpUsernameViewController { viewController.fullName = fullName viewController.email = email viewController.streetAddress = streetAddress viewController.zipNumber = zipNumberInput.text viewController.postalArea = postalAreaLabel.text } } } func getPostalArea() { var url = NSURL(string: "https://api.bring.com/shippingguide/api/postalCode.xml?clientUrl=insertYourClientUrlHere&country=no&pnr=" + (zipNumberInput.text)!) var xmlParser = NSXMLParser(contentsOfURL: url!) xmlParser!.delegate = self xmlParser!.parse() } func parser(parser: NSXMLParser, foundCharacters string: String) { if(string == "Ugyldig postnummer") { postalAreaLabel.enabled = true postalAreaLabel.text = "Unknown zip number" createAccountButton.enabled = false } else if(string != "\n " && string != "\n \n") { createAccountButton.enabled = true postalAreaLabel.enabled = true postalAreaLabel.text = string } } }
true
8be603008846261d30e3f2951367ccbbd8e88585
Swift
MrLotU/SwiftHooksDiscord
/Sources/Discord/State/State.swift
UTF-8
2,043
2.796875
3
[]
no_license
import NIOConcurrencyHelpers public final class State { private let lock: Lock private var _channels: [Channel] private var _guilds: [Guild] private var _dms: [Channel] private var _users: [User] private var _me: User! internal init() { self.lock = Lock() self._channels = [] self._guilds = [] self._dms = [] self._users = [] self._me = nil } } public extension State { internal(set) var channels: [Channel] { get { self.lock.withLock { self._channels } } set { self.lock.withLockVoid { self._channels = newValue } } } internal(set) var guilds: [Guild] { get { self.lock.withLock { self._guilds } } set { self.lock.withLockVoid { self._guilds = newValue } } } internal(set) var dms: [Channel] { get { self.lock.withLock { self._dms } } set { self.lock.withLockVoid { self._dms = newValue } } } internal(set) var users: [User] { get { self.lock.withLock { self._users } } set { self.lock.withLockVoid { self._users = newValue } } } internal(set) var me: User { get { self.lock.withLock { self._me } } set { self.lock.withLockVoid { self._me = newValue } } } } extension Array where Element: Snowflakable & DiscordHandled { subscript (flake: Snowflake) -> Element? { get { return self.first { $0.snowflakeDescription == flake } } set { defer { if var val = newValue { val.client = nil self.append(val) } } guard let index = self.firstIndex(where: { $0.snowflakeDescription == flake }) else { return } self.remove(at: index) } } }
true
f627800a5769ef0cfbd006ad4a10b723a6829fa6
Swift
dannyCaiHaoming/MyGitProject
/剑指Offer/剑指Offer/main.swift
UTF-8
58,236
3.703125
4
[]
no_license
// // main.swift // 剑指Offer // // Created by Danny on 2019/8/24. // Copyright © 2019 Danny. All rights reserved. // import Foundation public class TreeNode { public var val: Int public var left: TreeNode? public var right: TreeNode? public init(_ val: Int) { self.val = val self.left = nil self.right = nil } } //MARK: 面试3:数组中重复的数字 ///题目一:找出数组中重复的数字 func duplicate(numbers:[Int]) -> Int? { if numbers.isEmpty { return nil } var newNumbers = numbers for (index,value) in newNumbers.enumerated() { if value < 0 || value > newNumbers.count { return nil } //如果下标和数值不一样,就替换数值到对应下标处,如果该下标已经有了,则返回该数值 while value != index { if value == newNumbers[value]{ return value } let temp = numbers[value] newNumbers[value] = value newNumbers[index] = temp } } return nil } ///题目二:不修改数组找出重复的数字 func getDuplication(numbers:[Int]) -> Int? { if numbers.isEmpty { return nil } //这里的start和end是表示数字的,不是表示数组下标 var start = 1 var end = numbers.count - 1 while start <= end { let mid = (end - start)/2 + start let count = countRange(numbers: numbers, start: start, end: mid) if start == end { ///////似乎二分法最后结束条件都会前等于后 if count > 1 { return start }else { break } } if count > mid - start + 1{ end = mid }else { start = mid + 1 } } return nil } func countRange(numbers:[Int],start:Int,end:Int) -> Int{ if numbers.isEmpty { return 0 } var count = 0 for (_,value) in numbers.enumerated() { if value >= start && value <= end { count += 1 } } return count } //MARK: 面试题4 二维数组中的查找 ///题目: func Find(numbers:[Int],rows:Int,columns:Int,number:Int) -> Bool { var row_ = 0 var column_ = columns - 1 if numbers.isEmpty || numbers.count < rows * columns { return false } while (row_ <= rows - 1) && column_ >= 0 { if numbers[columns * row_ + column_] > number { //右上比Target大,这一列都不要 column_ -= 1 continue } if numbers[columns * row_ + column_] < number { //右上比Target小,这一行都不要 row_ += 1 continue } if numbers[columns * row_ + column_] == number { return true } } return false } //MARK: 面试题5: 替换空格 ///题目: func ReplaceBlank( string:inout [Character]){ var newString = string for char in string { if char == " " { newString.append(contentsOf: [" "," "]) } } var p1 = string.count - 1 var p2 = newString.count - 1 while p1 >= 0 && p2 > 0 { if newString[p1] == " "{ newString[p2] = "0" p2 -= 1 newString[p2] = "2" p2 -= 1 newString[p2] = "%" p2 -= 1 p1 -= 1 }else{ newString[p2] = newString[p1] p2 -= 1 p1 -= 1 } print(newString) } string = newString } //MARK: 面试题6:从尾到头打印链表 ///题目: class ListNode<T:Equatable>:Equatable{ static func == (lhs: ListNode<T>, rhs: ListNode<T>) -> Bool { // return (lhs.value == rhs.value) && (lhs.pNext == rhs.pNext) return lhs === rhs } var value:T? var pNext: ListNode<T>? init(value: T?,next:ListNode<T>?) { self.value = value self.pNext = next } } func PrintListReversingly_Recursively(pHead:ListNode<Int>) { if pHead.pNext != nil { PrintListReversingly_Recursively(pHead: pHead.pNext!) } print(pHead.value!) } //MARK: 面试题7:重建二叉树 ///题目: class BinaryTreeNode<T:Equatable>:Equatable { static func == (lhs: BinaryTreeNode<T>, rhs: BinaryTreeNode<T>) -> Bool { return lhs.value == rhs.value && lhs.pLeft == rhs.pLeft && lhs.pRight == rhs.pRight && lhs.pParent == rhs.pParent } var value:T? var pLeft:BinaryTreeNode<T>? var pRight:BinaryTreeNode<T>? var pParent:BinaryTreeNode<T>? init(value:T?,left:BinaryTreeNode<T>?,right:BinaryTreeNode<T>?) { self.value = value self.pLeft = left self.pRight = right } init(value:T?,left:BinaryTreeNode<T>?,right:BinaryTreeNode<T>?,parent:BinaryTreeNode<T>?) { self.value = value self.pLeft = left self.pRight = right self.pParent = parent } } func Contruct(preorder:[Int],inorder:[Int]) -> BinaryTreeNode<Int>? { if preorder.isEmpty || inorder.isEmpty || (preorder.count != inorder.count) { return nil } return ConstructCore(preorder: preorder, inorder: inorder) } func ConstructCore(preorder:[Int],inorder:[Int]) -> BinaryTreeNode<Int>? { if preorder.isEmpty && inorder.isEmpty { return nil } let firstRoot = inorder.firstIndex(of: preorder[0])! // let inleftCount:Int = firstRoot //3 var leftTree:BinaryTreeNode<Int>? = nil if firstRoot >= 1 { leftTree = ConstructCore(preorder: Array(preorder[1...firstRoot]), inorder: Array(inorder[0..<firstRoot])) } let rightPreStart:Int = firstRoot + 1 var rightTree:BinaryTreeNode<Int>? = nil if firstRoot+1 < inorder.count { rightTree = ConstructCore(preorder: Array(preorder[rightPreStart..<preorder.count]), inorder: Array(inorder[firstRoot+1..<inorder.count])) } let tree = BinaryTreeNode.init(value: preorder[0], left: leftTree, right: rightTree) return tree } //MARK: 面试题8:二叉树的下一个节点 ///题目: func GetNext(pNode:BinaryTreeNode<Int>?) -> BinaryTreeNode<Int>? { guard let pRoot = pNode, pRoot.pLeft == nil && pRoot.pRight == nil else { return nil } //存在右子树 if pNode?.pRight != nil { return pNode?.pRight } //是父节点的左子树 if pNode?.pParent != nil && pNode?.pParent?.pLeft == pNode { return pNode?.pParent } var parent = pNode?.pParent //如果二者都不是,就需要向上查找到是某父节点的左子树 while parent != nil { if parent?.pParent != nil && parent!.pParent?.pLeft == parent { return parent } parent = parent?.pParent } return nil } //MARK: 面试题9:用两个栈实现队列 ///题目: struct Stack<T> { var sequence:[T] = [] mutating func push(element:T) { sequence.append(element) } mutating func pop() -> T? { return sequence.popLast() } func top() -> T? { return sequence.last } } struct Queue<T> { var stack1:Stack<T> = Stack.init() var stack2:Stack<T> = Stack.init() mutating func appendTail(element:T) { stack1.push(element: element) } mutating func deleteHead() -> T? { if stack2.top() == nil { while stack1.top() != nil { stack2.push(element: stack1.pop()!) } } return stack2.pop() } } //MARK: 面试题10 斐波那契数列 ///题目一:求斐波那契数列的第n项 func Fibonacci(n:Int) -> Int { if n <= 0 { return 0 } if n == 1 { return 1 } return Fibonacci(n:n-1) + Fibonacci(n:n-2) } func Fibonacci1(n:Int) -> Int { var front = 0 var back = 1 var count = n while count >= 2 { let temp = front + back front = back back = temp count -= 1 } return back } ///题目二:青蛙跳台阶问题 func FragJump(n:Int) -> Int { if n == 0 { return 0 } if n == 1 { return 1 } if n == 2 { return 2 } return FragJump(n: n-1) + FragJump(n: n-2) } //MARK:查找算法 ///顺序查找 func OrderSearch(list:[Int],n:Int) -> Int?{ for int in list { if int == n { return int } } return nil } ///二分查找 func BinarySearch(list:[Int],n:Int) -> Int?{ var front = 0 var back = list.count - 1 var mid = list.count / 2 while back >= front { mid = (back - front) / 2 + front if list[mid] == n { return n } if list[mid] > n { //取前面 back = mid - 1 }else { front = mid + 1 } } return nil } ///哈希查找 ///二叉排序树查找 func BinarySearchTree(tree:BinaryTreeNode<Int>?,value:Int) -> BinaryTreeNode<Int>? { var currentNode = tree while currentNode != nil { if currentNode!.value! == value { return currentNode } if currentNode!.value! > value { currentNode = currentNode!.pLeft continue } if currentNode!.value! < value { currentNode = currentNode!.pRight continue } } return nil } //MARK: 排序算法 ///冒泡排序 func BubbleSort(list:inout [Int]) { var back = list.count while back > 0 { for index in 0..<back-1 { if list[index] > list[index+1] { let temp = list[index+1] list[index+1] = list[index] list[index] = temp } } back -= 1 } print(list) } ///选择排序 func SelectionSort(list:inout [Int]){ if list.isEmpty || list.count <= 1 { return } for i in (1...list.count-1).reversed() { for j in 0...i-1{ if list[j] > list[j+1] { let temp = list[j+1] list[j+1] = list[j] list[j] = temp } } } print(list) } ///插入排序 func InsertSort(list:inout [Int]){ for start in 0..<list.count { var temp = list[start]//当前操作要做插入的元素 for i in 0..<start { if temp < list[i] { let t = list[i] list[i] = temp temp = t } } list[start] = temp } print(list) } func InsertSort1(list:inout [Int]){ if list.count == 1 { return } var temp = 0 for i in 1..<list.count { if list[i] < list[i-1] { temp = list[i] list[i] = list[i-1] var j = i-1 while j >= 0 && list[j] > temp { list[j+1] = list[j] j -= 1 } list[j+1] = temp } } print(list) } ///希尔排序 func ShellSort(list:inout [Int]){ var length = list.count / 2 while length >= 1 { var i = 0 while i < list.count { var temp = list[i] var j = 0 while j < i { if temp < list[j] { let t = list[j] list[j] = temp temp = t } if j+length >= i{ list[j+length] = temp } j += length } i += length } length /= 2 } print(list) } func ShellSort1(list: inout [Int]) { var length = list.count / 2 while length >= 1 { for var i in 0..<list.count { for var j in i..<list.count { if list[j] < list[i] { let temp = list[i] list[i] = list[j] list[j] = temp } j += length } i += length } length /= 2 } print(list) } ///归并排序 func MergeSort(list:[Int]) -> [Int] { return CoreMergeSort(list: list) } func CoreMergeSort(list:[Int]) -> [Int] { if list.count/2 < 1 { return list } let newMid = list.count/2 let leftList = CoreMergeSort(list: Array(list[0..<newMid])) let rightList = CoreMergeSort(list: Array(list[newMid..<list.count])) var newList:[Int] = [] var i = 0 var j = 0 while i < leftList.count && j < rightList.count { if leftList[i] <= rightList[j]{ newList.append(leftList[i]) i += 1 continue }else { newList.append(rightList[j]) j += 1 continue } } while i < leftList.count { newList.append(leftList[i]) i += 1 } while j < rightList.count { newList.append(rightList[j]) j += 1 } return newList } ///快速排序 func QuickSort(list:inout [Int]) { if list.count <= 1 { return } let index = Partition1(list: &list, start: 0, end: list.count - 1) var left = Array(list[0...index]) var right = Array(list[index+1..<list.count]) QuickSort(list: &left) QuickSort(list: &right) list = left + right // print(list) } ///划分左小右大 返回划分位置 func Partition(list:inout [Int],start:Int,end:Int) -> Int { //将基准数放到最后,调整的时候就不会影响到 //将小的往前面放,并记录下放的位置 var index = 0 list.swapAt(0, end) for i in start..<end { if list[end] >= list[i] { list.swapAt(index, i) index += 1 } } list.swapAt(index, end) print(list) return index } func Partition1(list:inout [Int],start:Int,end:Int) -> Int { //将基准数放到最后,调整的时候就不会影响到 //将小的往前面放,并记录下放的位置 var i = start var j = end let mark = list[i] while i < j { while i < j, list[j] >= mark { //从后找出比基准值小的挪到前面 j -= 1 } list[i] = list[j] while i < j, list[i] <= mark { //从前找出基准值比大的挪到后面 i += 1 } list[j] = list[i] } list[i] = mark print(list) return i } ///堆排序 ///构建大顶堆 func BuildMaxHeap(list:inout [Int]){ if list.count/2-1 < 0 { return } for i in (0...list.count/2-1).reversed() { AdjustHeap(list: &list, index: i,length: list.count) } } func AdjustHeap(list:inout [Int],index:Int,length:Int){ var maxIndex = index let left = 2*index+1 let right = 2*index+2 //存在左子节点 if left < length && list[left] > list[maxIndex] { maxIndex = left } //存在右子节点 if right < length && list[right] > list[maxIndex] { maxIndex = right } if maxIndex != index { list.swapAt(maxIndex, index) AdjustHeap(list: &list, index: maxIndex,length: length) } print(list) } // 只能调整一个节点的根节和左右字数 func HeapAdjust(list: inout [Int], s: Int, m: Int){ var temp = list[s]; var start = s var index = 2*start+1; var j = 2*start+1 while j <= m { if j < m, list[j] < list[j+1] { j += 1 } if temp > list[j] { break } list[start] = list[j] start = j; j = j * 2 + 1 index = start; } list[index] = temp; print(list) } func HeapSort1(list: inout [Int], n: Int) { for var i in (0...n/2-1).reversed() { HeapAdjust(list: &list, s: i, m: n-1) print(list) i -= 1 } print(list) } func HeapSort(list: inout [Int]) { BuildMaxHeap(list: &list) var i = list.count - 1 print(list) while i > 0 { list.swapAt(i, 0) i -= 1 AdjustHeap(list: &list, index: 0,length: i) print(list) } print(list) } ///桶排序 //TODO: 没写 //MARK: 面试题11:旋转数组的最小数字 func Min(list:[Int],start:Int,end:Int) -> Int { var s = start var e = end if list[e] > list[s] { return list[s] } var mid = (e-s)/2 while s != mid { if list[s] == list[mid] && list[e] == list[mid]{ ///如果头,中间,尾都相等,则不能判断出最小值在哪个区间 return MinInSort(list: Array(list[s...e])) } if list[mid] >= list[s] { s = mid + 1 } if list[mid] <= list[e] { e = mid - 1 } mid = (s-e)/2+s } return list[mid+1] } func MinInSort(list:[Int]) -> Int { var min = list[0] for i in 0..<list.count{ if list[i] < min { min = list[i] } } return min } //MARK: 面试题12: 矩阵中的路径 //row,colum表示二位数组多大而已 func HasPath(list:[Character],rows:Int,columns:Int,matchStr:[Character]) -> Bool { //1.从任意出发 //2.走过的不能走 //3.边界的值不能走 var selectedList:[Int] = [] for _ in 0..<rows * columns { selectedList.append(0) } var hasPath = false for r in 0..<rows { for c in 0..<columns { if list[r*columns+c] == matchStr[0] { let firstTime = CoreHasPath(list: list, rows: rows, columns: columns, row: r, column: c, matchStr: Array(matchStr[0..<matchStr.count]), selectedList: &selectedList) hasPath = hasPath || firstTime } } } return hasPath } //row,column表示位置在哪儿 func CoreHasPath(list:[Character],rows:Int,columns:Int,row:Int,column:Int,matchStr:[Character],selectedList:inout [Int]) -> Bool{ //需要分上左下右四个情况 var hasPath = false if row >= 0 && row < rows && column >= 0 && column < columns && selectedList[row*columns+column] == 0 && list[row*columns+column] == matchStr[0]{ selectedList[row*columns+column] = 1 if matchStr.count == 1 { return true } //上 let top = CoreHasPath(list: list, rows: rows, columns: columns, row: row-1, column: column, matchStr: Array(matchStr[1..<matchStr.count]), selectedList: &selectedList) //左 let left = CoreHasPath(list: list, rows: rows, columns: columns, row: row, column: column-1, matchStr: Array(matchStr[1..<matchStr.count]), selectedList: &selectedList) //下 let bottom = CoreHasPath(list: list, rows: rows, columns: columns, row: row+1, column: column, matchStr: Array(matchStr[1..<matchStr.count]), selectedList: &selectedList) //右 let right = CoreHasPath(list: list, rows: rows, columns: columns, row: row, column: column+1, matchStr: Array(matchStr[1..<matchStr.count]), selectedList: &selectedList) hasPath = top || left || bottom || right if hasPath == false { selectedList[row*columns+column] = 0 } } return hasPath } //MARK: 面试题13: 机器人的运动范围 //MARK: 面试题 14 剪绳子 ///动态规划 func MaxProductAfterCutting_Solution1(length: Int) -> Int{ if length < 2 { return 0 } if length == 2 { return 1 } if length == 3 { return 2 } var products:[Int] = [0,1,2,3] var max = 0 for i in 4...length { //第一层循环,由开始数字,一个个计算f(4),f(5),f(6)等等子问题的最大值,到时候的f(n) = f(n-m)+f(m)子问题组成结果 max = 0 for j in 1...i/2{ //第二层循环,计算子问题最大乘积记录下来,用作当前问题的结果供后面更大的问题使用 let product = products[j] * products[i-j] if product > max { max = product } } products.append(max) } return products[length] } ///贪婪算法 func MaxProductAfterCutting_Solution2(length: Int) -> Int{ //就是穷举出最优解的几种情况,或者每次能有规律找出最优解,从而叠加起来完成最优解的情况 //这道题中就是分成f(5)就是找f(2)*f(3),f(4)=f(2)*f(2),所以就是解决最多能细分几个4,几个3 var l = length // var products:[Int] = [0,0,1,2,4] var time = 0 var result = 0 while l/4 >= 1 { result *= 4 l -= 4 } if l >= 3 { result *= 2 } result *= l return result } //MARK:面试题15: 二进制中1的个数(整数带正和负的) //func NumberOf1(n:Int) -> Int { // var m = n // var count = 0 // // while m/2 > 0 { // if m%2 != 0 { // count += 1 // } // m /= 2 // if m == 1 { // count += 1 // break // } // } // // return count // //} //负数的表示方式使用二进制的补码,就是先按位取反再加一 func NumberOf1(n:Int8) -> Int { var flag:Int8 = 0b00000001 var count = 0 while flag > 0 { if n&flag > 0 { count += 1 } flag = flag<<1 } return count } //二进制数-1再与自身&运算,将会将最后一个1消除 func NumberOf1_1(n:Int8) -> Int { var newN = n var count = 0 while newN > 0 { newN = (newN-1)&newN count += 1 } return count } //MARK:面试题16: 数值的整数次方 func MyPower(base:Double,exponent:Int) -> Double { if base.isEqual(to: 0.0) { return 0.0 } var p = MyPositivePower1(base: base, exponent: abs(exponent)) if exponent < 0 { p = 1/p } return p } ///简单的循环解决 func MyPositivePower(base:Double,exponent:Int) -> Double{ var result = 1.0 for _ in 0..<exponent { result *= base } return result } ///使用斐波那契数列公式解决 func MyPositivePower1(base:Double,exponent:Int) -> Double{ if exponent == 0 { return 1 } if exponent == 1 { return base } let half = MyPositivePower1(base: base, exponent: exponent>>1) var result = half * half if exponent&(0b1) == 1 { result *= base } return result } //MARK: 面试题17:打印从1到最大的n位数 func Print1ToMaxOfNDigits(n:Int){ var list:[Int] = [] for _ in 0..<n { list.append(0) } var stop = false while stop == false { stop = Increment(list: &list) PrintList(list: list) } } func Increment(list: inout[Int]) -> Bool { var addOne = 0 list[list.count-1] += 1 for i in (0..<list.count).reversed() { list[i] = list[i] + addOne addOne = 0 if list[i] >= 10 { addOne = 1 list[i] = list[i] - 10 } if i == 0 && addOne == 1 { return true } } return false } func PrintList(list:[Int]){ var str = "" var ignore = true for value in list{ if ignore == true && value == 0 { continue } ignore = false str = str + " \(value)" } print(str) } //MARK:面试题18:删除链表的节点 ///题目一:在O(1)时间内删除链表节点 func DeleteNode(pListHead:inout ListNode<Int>?,pToBeDeleted: ListNode<Int>){ //判断是否在头结点 //判断是否在末尾 //判断是否为空 if pListHead == nil || pListHead!.value == nil { return } if pListHead == pToBeDeleted { pListHead = pListHead!.pNext } var next = pToBeDeleted.pNext if next != nil { pToBeDeleted.value = next?.value pToBeDeleted.pNext = next?.pNext //清理不用的数据 next = nil }else{ while pListHead?.pNext != nil { if pListHead?.pNext == pToBeDeleted { pListHead?.pNext = nil } pListHead = pListHead?.pNext } } } ///题目二:删除链表中重复的节点 func DeleteDuplication(pHead:inout ListNode<Int>?){ //判断链表为空 //链表只有一个的情况 //链表所有内容都相等的情况 //链表开头都相等的情况 //链表结尾都相等的情况 if pHead == nil || pHead!.value == nil { return } var preNode:ListNode<Int>? = nil var head = pHead while head != nil { if head?.pNext?.value == head?.value { //重复的,遍历到不重复的 let temp = head while head != nil { if head!.value! > temp!.value! { break } head = head?.pNext } if preNode == nil { preNode = head }else { preNode?.pNext = head } }else{ if preNode == nil { preNode = head }else { preNode?.pNext = head preNode = preNode?.pNext } head = head?.pNext } } } //MARK:面试题19:正则表达式匹配 ///题目 func Match(str:[Character],pattern:[Character]) -> Bool { // if str[0] != pattern[0] && pattern[0] != "." { // return false // } if str.isEmpty && pattern.isEmpty { return true } if str.isEmpty && !pattern.isEmpty { return false } if pattern.count > 1 && pattern[1] == "*" { //特殊模式 if pattern[0] == str[0] || (pattern[0] == "." && !str.isEmpty){ //这里有三种情况 //1.将*和前面的符号忽略,匹配串移动2个 //2.将*和前面的符号跟字符串匹配一个,字符串移动一个跟匹配串移动两个 //3.匹配下一个字符串,匹配串不动,字符串移动一个 return Match(str: str, pattern: Array(pattern[2..<pattern.count])) || Match(str: Array(str[1..<str.count]), pattern: Array(pattern[1..<pattern.count])) || Match(str: Array(str[1..<str.count]), pattern: pattern) }else{ //由于星号前的字符不匹配,所以必须忽略掉 return Match(str: str, pattern: Array(pattern[2..<pattern.count])) } } if str[0] == pattern[0] || (pattern[0] == "." && !str.isEmpty){ return Match(str: Array(str[1..<str.count]), pattern: Array(pattern[1..<pattern.count])) } return false } //func Match2(str:[Character],pattern:[Character]) -> Bool{ // // var i = 0 // var j = 0 // while i < str.count && j < pattern.count { // // if j+1 < pattern.count && pattern[j+1] == "*" { // // if pattern[j] == str[i] || pattern[j] == "."{ // // // } // // // } // } //} //MARK:面试题20:表示数值的字符串 ///题目 //- A[.[B]][e|EC] //- .B[e|EC] func IsNumberic(str:[Character]) -> Bool { if str.isEmpty { return false } var numeric = ScanInteger(str: str) if numeric.1 == str.count { return numeric.0 } if str[numeric.1] == "." { //A之后跟着小数点的话 let result = ScanUnsignedInteger(str: Array(str[numeric.1+1..<str.count])) numeric.0 = numeric.0 || result.0 numeric.1 += result.1 } if str[numeric.1] == "e" || str[numeric.1] == "E" { //如果是指数的话 if numeric.1+1 == str.count { //指数末尾还要跟着数字 return false } let result = ScanInteger(str: Array(str[numeric.1+1..<str.count])) numeric.0 = numeric.0 && result.0 numeric.1 += result.1 } return numeric.0 && (numeric.1 + 1 == str.count) } func ScanInteger(str:[Character]) -> (Bool,Int) { var start = 0 if str[0] == "+" || str[0] == "-" { start = 1 } let result = ScanUnsignedInteger(str: Array(str[start..<str.count])) let index = result.0 == true ? result.1 + start : 0 return (result.0,index) } func ScanUnsignedInteger(str:[Character]) -> (Bool,Int) { var index = 0 if !str.isEmpty { while index < str.count { if str[index] >= "0" && str[index] <= "9"{ index += 1 continue } break } return (index != 0, index) } return (false,0) } //MARK:面试题21:调整数组顺序使奇数位于偶数前面 ///题目 func ReorderOddEvent(pdata: inout [Int]){ var front = 0 var back = pdata.count - 1 while back > front { while front<back && pdata[front]&1 == 1{ front += 1 } while front<back && pdata[back]&1 == 0 { back -= 1 } if pdata[front]&1 == 0 && pdata[back]&1 == 1{ //前面是偶数,后面是奇数 let temp = pdata[front] pdata[front] = pdata[back] pdata[back] = temp front += 1 back -= 1 } } print(pdata) } //MARK: 面试题22:链表中倒数第k个节点 //题目: func FindKthToTail(pListHead:ListNode<Int>,k:Int) -> ListNode<Int>? { var front:ListNode<Int>? = pListHead var back:ListNode<Int>? = pListHead var count = 1 while back != nil && count < k { back = back?.pNext count += 1 } if back == nil { return nil } while back?.pNext != nil && front != nil { back = back?.pNext front = front!.pNext } return front } //MARK: 面试题23:链表中环的入口节点 ///题目 func EntryNodeOfLoop(pHead:ListNode<Int>) -> ListNode<Int>? { var one:ListNode<Int>? = pHead var two:ListNode<Int>? = pHead while two != nil { one = one?.pNext two = two?.pNext?.pNext if one == two { return one } } return nil } //MARK:面试题24:翻转链表 ///题目 func ReverseList(pHead:inout ListNode<Int>?) -> ListNode<Int>? { if pHead == nil || pHead?.pNext == nil { return pHead } var preNode:ListNode<Int>? = nil while pHead != nil { let temp = pHead?.pNext pHead?.pNext = preNode let newPre = pHead newPre?.pNext = preNode preNode = newPre pHead = temp } return preNode } //MARK:面试题25:合并两个排序的链表 ///题目 func Merge(pHead1: inout ListNode<Int>?,pHead2: inout ListNode<Int>?) ->ListNode<Int>? { var newHead:ListNode<Int>? var pHead:ListNode<Int>? while pHead1 != nil && pHead2 != nil { if pHead1!.value! < pHead2!.value! { if newHead == nil { newHead = pHead1 pHead = newHead }else { newHead?.pNext = pHead1 newHead = newHead?.pNext } pHead1 = pHead1?.pNext }else { if newHead == nil { newHead = pHead2 pHead = newHead }else { newHead?.pNext = pHead2 newHead = newHead?.pNext } pHead2 = pHead2?.pNext } } while pHead1 != nil { if newHead == nil { newHead = pHead1 pHead = newHead }else { newHead?.pNext = pHead1 newHead = newHead?.pNext } pHead1 = pHead1?.pNext } while pHead2 != nil { if newHead == nil { newHead = pHead2 pHead = newHead }else { newHead?.pNext = pHead2 newHead = newHead?.pNext } pHead2 = pHead2?.pNext } return pHead } func Merge2(pHead1: inout ListNode<Int>?,pHead2: inout ListNode<Int>?) ->ListNode<Int>? { var newHead:ListNode<Int>? if pHead1 == nil && pHead2 == nil { return nil } if pHead1 == nil { return pHead2 } if pHead2 == nil { return pHead1 } if pHead1!.value! < pHead2!.value! { newHead = pHead1 var newPhead1 = pHead1?.pNext newHead?.pNext = Merge2(pHead1: &newPhead1, pHead2: &pHead2) // if pHead1?.pNext == nil { // return pHead1 // } // var newPhead1 = pHead1?.pNext // if newHead == nil { // newHead = Merge2(pHead1: &newPhead1, pHead2: &pHead2) // }else { // newHead?.pNext = Merge2(pHead1: &newPhead1, pHead2: &pHead2) // } }else{ newHead = pHead2 var newPhead2 = pHead2?.pNext newHead?.pNext = Merge2(pHead1: &pHead1, pHead2: &newPhead2) // if pHead2?.pNext == nil { // return pHead2 // } // var newPhead2 = pHead2?.pNext // if newHead == nil { // newHead = Merge2(pHead1: &pHead1, pHead2: &newPhead2) // }else { // newHead?.pNext = Merge2(pHead1: &pHead1, pHead2: &newPhead2) // } } return newHead } //MARK:面试题26:输的子结构 ///题目: func HasSubTree(treeA:BinaryTreeNode<Int>? ,treeB:BinaryTreeNode<Int>?) -> Bool { var result:Bool = false if treeA != nil && treeB != nil { if treeA?.value == treeB?.value { result = CoreHadSubTree(treeA: treeA, treeB: treeB) } if !result == true { result = CoreHadSubTree(treeA: treeA?.pLeft, treeB: treeB) } if !result == true { result = CoreHadSubTree(treeA: treeA?.pRight, treeB: treeB) } } return result } func CoreHadSubTree(treeA:BinaryTreeNode<Int>? ,treeB:BinaryTreeNode<Int>?) -> Bool { if treeB == nil { return true } if treeA == nil { return false } return CoreHadSubTree(treeA: treeA?.pLeft, treeB: treeB?.pLeft) && CoreHadSubTree(treeA: treeA?.pRight, treeB: treeB?.pRight) } //MARK: 面试题27:二叉树的镜像 func MirrorRecursively(pNode:BinaryTreeNode<Int>?) -> BinaryTreeNode<Int>?{ if pNode?.pLeft == nil && pNode?.pRight == nil { return pNode } pNode?.pLeft = MirrorRecursively(pNode: pNode?.pLeft) pNode?.pRight = MirrorRecursively(pNode: pNode?.pRight) let temp = pNode?.pLeft pNode?.pLeft = pNode?.pRight pNode?.pRight = temp return pNode } //MARK: 面试题28:对称二叉树 func IsSymmetrical(pRoot :BinaryTreeNode<Int>?) -> Bool { if (pRoot == nil) || (pRoot?.pLeft == nil && pRoot?.pRight == nil) { return true } if pRoot?.pLeft == nil || pRoot?.pRight == nil { return false } return IsSymmetrical(pRoot1: pRoot?.pLeft, pRoot2: pRoot?.pRight) } func IsSymmetrical(pRoot1:BinaryTreeNode<Int>?,pRoot2:BinaryTreeNode<Int>?) ->Bool{ if pRoot1 == nil && pRoot2 == nil { return true } return (pRoot1?.value == pRoot2?.value) && IsSymmetrical(pRoot1: pRoot1?.pLeft, pRoot2: pRoot2?.pRight) && IsSymmetrical(pRoot1: pRoot1?.pRight, pRoot2: pRoot2?.pLeft) } //MARK:面试题29:顺时针打印矩阵 func spiralOrder(_ matrix: [[Int]]) -> [Int] { var Rs = 0 var Cs = 0 var Re = matrix.count-1 if matrix.isEmpty || matrix[0].isEmpty{ return [] } var Ce = matrix[0].count-1 var result:[Int] = [] while true { //Column 左到右 if (Re >= Rs && Ce >= Cs) == false { break } for column in Cs...Ce{ result.append(matrix[Rs][column]) } Rs += 1 if (Re >= Rs && Ce >= Cs) == false { break } //Row 上到下 for row in Rs...Re { result.append(matrix[row][Ce]) } Ce -= 1 if (Re >= Rs && Ce >= Cs) == false { break } //Column 右到左 for column in (Cs...Ce).reversed(){ result.append(matrix[Re][column]) } Re -= 1 if (Re >= Rs && Ce >= Cs) == false { break } //Row 下到上 for row in (Rs...Re).reversed() { result.append(matrix[row][Cs]) } Cs += 1 } return result } //MARK: 面试题30:包含min函数的栈 //题目: class MinStack { var helper:[Int] = [] var stack:[Int] = [] /** initialize your data structure here. */ init() { } func push(_ x: Int) { stack.append(x) if helper.isEmpty { helper.append(x) return } if x < helper.last! { helper.append(x) }else{ helper.append(helper.last!) } } func pop() { stack.removeLast() helper.removeLast() } func top() -> Int { if stack.last == nil { return 0 } return stack.last! } func getMin() -> Int { if helper.last == nil { return 0 } return helper.last! } } //MARK:面试题31:栈的压入,弹出序列 ///题目 func validateStackSequences(_ pushed: [Int], _ popped: [Int]) -> Bool { var stack :Stack<Int> = Stack.init() var Push = pushed var Pop = popped while true { if Push.isEmpty { if (Pop.first != stack.top()) { return false } if Pop.isEmpty && stack.top() == nil { return true } } if stack.top() == Pop.first { _ = stack.pop() Pop.remove(at: 0) continue } if !Push.isEmpty{ stack.push(element: Push.first!) Push.remove(at: 0) } } } //MARK: 面试题32:从上到下打印二叉树 ///题目一:不分行从上到下打印二叉树 func PrintFromTopToBottom(pTreeRoot:BinaryTreeNode<Int>) -> [Int]{ var result:[Int] = [] var queue = Queue<BinaryTreeNode<Int>>() queue.appendTail(element: pTreeRoot) while let delete = queue.deleteHead() { result.append(delete.value!) if delete.pLeft != nil { queue.appendTail(element: delete.pLeft!) } if delete.pRight != nil { queue.appendTail(element: delete.pRight!) } } return result } ///题目二:分行从上到下打印二叉树 func levelOrder(_ root: BinaryTreeNode<Int>?) -> [[Int]] { guard let tree = root else { return [] } var numOfRow = 0 var numToDelete = 1 var result:[[Int]] = [] var row:[Int] = [] var queue:[BinaryTreeNode<Int>] = [] queue.append(tree) while queue.count > 0 { let delete = queue.remove(at: 0) numToDelete -= 1 row.append(delete.value!) if delete.pLeft != nil { queue.append(delete.pLeft!) numOfRow += 1 } if delete.pRight != nil { queue.append(delete.pRight!) numOfRow += 1 } if numToDelete == 0 { result.append(row) row.removeAll() numToDelete = numOfRow numOfRow = 0 } } return result } ///题目三:之字形打印二叉树 func PrintTreeInZhi(pRoot:BinaryTreeNode<Int>?) -> [[Int]]{ var result:[[Int]] = [] if pRoot == nil { return result } var leftStack:Stack<BinaryTreeNode<Int>> = Stack() var rightStack:Stack<BinaryTreeNode<Int>> = Stack() leftStack.push(element: pRoot!) while leftStack.top() != nil || rightStack.top() != nil { var row:[Int] = [] if leftStack.top() != nil { while leftStack.top() != nil { let top = leftStack.pop()! row.append(top.value!) if top.pLeft != nil { rightStack.push(element: top.pLeft!) } if top.pRight != nil { rightStack.push(element: top.pRight!) } } result.append(row) }else{ while rightStack.top() != nil { let top = rightStack.pop()! row.append(top.value!) if top.pRight != nil { leftStack.push(element: top.pRight!) } if top.pLeft != nil { leftStack.push(element: top.pLeft!) } } result.append(row) } } return result } //MARK:面试题33:二叉搜索树的后序遍历序列 ///题目: func VerifySquenceOfBST(sequence:[Int]) -> Bool { if sequence.count <= 0 { return true } let root = sequence.last //寻找比root大的值,然后左侧都是左子树 var leftCount = 0 for i in 0..<sequence.count { if sequence[i] > root! { leftCount = i break } } var rightStart = leftCount while rightStart < sequence.count { if sequence[rightStart] < root! { return false } rightStart += 1 } var leftVerify = true if leftCount > 0 { leftVerify = VerifySquenceOfBST(sequence: Array(sequence[0..<leftCount])) } var rightVerify = true if leftCount < sequence.count - 1 { rightVerify = VerifySquenceOfBST(sequence: Array(sequence[leftCount..<sequence.count-1])) } return leftVerify && rightVerify } //MARK:面试题34:二叉树中和为某一值的路径 //题目 class Solution { var currentValue = 0 var stack:Stack<BinaryTreeNode<Int>> = Stack() var result:[[Int]] = [] func pathSum(_ root: BinaryTreeNode<Int>?, _ sum: Int) -> [[Int]] { if root == nil { return result } pathSumCore(root: root, sum: sum) return result } func pathSumCore(root:BinaryTreeNode<Int>?,sum:Int) { currentValue += root!.value! stack.push(element: root!) if root?.pLeft == nil && root?.pRight == nil && currentValue == sum { //将栈中所有内容放入结果 var row:[Int] = [] for tree in stack.sequence { row.append(tree.value!) } result.append(row) } if root?.pLeft != nil { pathSumCore(root: root?.pLeft, sum: sum) } // if left == false { // //如果左侧为假,将栈中节点恢复成原来 while stack.top() != root { let tree = stack.pop() currentValue -= tree!.value! } // } if root?.pRight != nil { pathSumCore(root: root?.pRight, sum: sum) } // if right == false { // //如果左侧为假,将栈中节点恢复成原来 while stack.top() != root { let tree = stack.pop() currentValue -= tree!.value! } // } let tree = stack.pop() currentValue -= tree!.value! } } //class Solution { // // var currentValue = 0 // var stack:Stack<TreeNode> = Stack() // var result:[[Int]] = [] // // func pathSum(_ root: TreeNode?, _ sum: Int) -> [[Int]] { // if root == nil { // return result // } // // _ = pathSumCore(root: root, sum: sum) // // return result // } // // func pathSumCore(root:TreeNode?,sum:Int) { // // currentValue += root!.val // stack.push(element: root!) // // if root?.left == nil && root?.right == nil && currentValue == sum { // // //将栈中所有内容放入结果 // var row:[Int] = [] // for tree in stack.sequence { // row.append(tree.val) // } // result.append(row) // // // } // // // if root?.left != nil { // pathSumCore(root: root?.left, sum: sum) // } // // // // if root?.right != nil { // pathSumCore(root: root?.right, sum: sum) // } // // let tree = stack.pop() // currentValue -= tree!.val // // // // // } //} //MARK:面试题35:复杂链表的复制 ///题目 class ComplexListNode<T> { var value:T var pNext:ComplexListNode<T>? var pSibling:ComplexListNode<T>? init(value:T,pNext:ComplexListNode<T>?,pSibling:ComplexListNode<T>?) { self.value = value self.pNext = pNext self.pSibling = pSibling } } func CopyComplexListNode(pHead:ComplexListNode<Int>?) -> ComplexListNode<Int>? { if pHead == nil { return nil } var copyPHead = pHead while copyPHead != nil { let copy:ComplexListNode = ComplexListNode.init(value: copyPHead!.value, pNext: copyPHead?.pNext, pSibling: nil) copyPHead?.pNext = copy copyPHead = copy.pNext } var sPHead = pHead while sPHead != nil { if sPHead?.pSibling != nil { //获取复制 let copy = sPHead?.pNext //将复制指针的任意指针,指向原来任意指针的下一个值 copy?.pSibling = sPHead?.pSibling?.pNext } sPHead = sPHead?.pNext?.pNext } let rPhead = pHead?.pNext var head = pHead?.pNext while head != nil { head?.pNext = head?.pNext?.pNext head = head?.pNext } return rPhead } //MARK:面试题36:二叉搜索树与双向链表 ///题目: func Convert(pRootOfTree:BinaryTreeNode<Int>?) -> BinaryTreeNode<Int>?{ if pRootOfTree == nil { return pRootOfTree } var new:BinaryTreeNode<Int>? = ConvertCore(pRootOfTree: pRootOfTree) while new?.pLeft != nil { if new?.pLeft == nil { break } new = new?.pLeft } return new } func ConvertCore(pRootOfTree:BinaryTreeNode<Int>?) -> BinaryTreeNode<Int>?{ if pRootOfTree == nil { return nil } if pRootOfTree?.pLeft == nil && pRootOfTree?.pRight == nil{ return pRootOfTree } var leftRoot = ConvertCore(pRootOfTree: pRootOfTree?.pLeft) //寻找leftRoot的最右 while leftRoot != nil { if leftRoot?.pRight == nil { break } leftRoot = leftRoot?.pRight } if leftRoot != nil { leftRoot?.pRight = pRootOfTree pRootOfTree?.pLeft = leftRoot } var rightRoot = ConvertCore(pRootOfTree: pRootOfTree?.pRight) //寻找rightRoot的最左 while rightRoot != nil { if rightRoot?.pLeft == nil { break } rightRoot = rightRoot?.pLeft } if rightRoot != nil { rightRoot?.pLeft = pRootOfTree pRootOfTree?.pRight = rightRoot } return pRootOfTree } //MARK:面试题37:序列化二叉树 //MARK:面试题38:字符串的排序 ///题目一:全排列 func permute(_ nums: [Int]) -> [[Int]] { if nums.count == 0 || nums.count == 1 { return [nums] } return permuteCore(nums) } func permuteCore(_ nums: [Int]) -> [[Int]] { if nums.count <= 1 { return [nums] } let afterPermute = permuteCore(Array(nums[1..<nums.count])) var newAfterResult:[[Int]] = [] for eachPermute in afterPermute { let arr = [nums[0]] + eachPermute newAfterResult.append(arr) } var result:[[Int]] = [] for eachPermute in newAfterResult { var permute = eachPermute if permute.count <= 1 { break } for index in 0..<permute.count { var temp = permute[0] permute[0] = permute[index] permute[index] = temp result.append(permute) temp = permute[0] permute[0] = permute[index] permute[index] = temp } } return result } var resultArray:[[Int]] = [] ///题目二:组合 func subsets(_ nums: [Int]) -> [[Int]] { if nums.count == 0 { return [nums] } if nums.count == 1 { return [nums,[]] } var pre:[Int] = [] subsetsCore1(nums, 0, &pre) return resultArray; } /// 递归将begin后面的剩余数字的组合逐次加进来,例如:[1,2,3],传入begin为1,则会返回2,23,3 /// - Parameter nums: 完整数字 /// - Parameter begin: 当前指定开始组合的位置 /// - Parameter pre: 组合前头的内容 func subsetsCore1(_ nums: [Int],_ begin:Int,_ pre:inout [Int]) { resultArray.append(pre) for i in begin..<nums.count { pre.append(nums[i]) subsetsCore1(nums, i+1, &pre) pre.removeLast() } } ///题目三:给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 //一样先搞顺序,有重复就跳过,并且都是从下标序号开始用后面的b排序 func subsetsWithDup(_ nums: [Int]) -> [[Int]] { let newNums = nums.sorted() var stack:Stack<Int> = Stack() subsetsWithDup(newNums, &stack, 0) return resultArray } func subsetsWithDup(_ nums:[Int],_ useArray:inout Stack<Int>,_ current:Int){ resultArray.append(useArray.sequence) for index in current..<nums.count { if index > current && nums[index] == nums[index-1] { continue } useArray.push(element: nums[index]) subsetsWithDup(nums, &useArray, index+1) useArray.pop() } } ///题目四:给定一个可包含重复数字的序列,返回所有不重复的全排列(回溯+去支) 这里用了的妙处,就是先把数组排列了,就方便找重复,上一次用完,如果连续相等,那么这次相当于同一层平行,就不会再用了 func permuteUnique(_ nums: [Int]) -> [[Int]] { if nums.count == 0 || nums.count == 1{ return [nums] } var useArray:[Int] = [] for _ in 0..<nums.count { useArray.append(0) } var preArray:[Int] = [] let newNums = nums.sorted() permuteUniqueCore(newNums,&preArray, &useArray, 0) return resultArray } func permuteUniqueCore(_ nums:[Int],_ preArray:inout [Int] ,_ useArray:inout [Int],_ currntRow:Int) { if currntRow == nums.count { resultArray.append(preArray) return } for index in 0..<nums.count { if useArray[index] == 0 { if index > 0 && nums[index - 1] == nums[index] && useArray[index-1] == 0{ continue } useArray[index] = 1 preArray.append(nums[index]) permuteUniqueCore(nums, &preArray, &useArray, currntRow+1) useArray[index] = 0 // row.removeLast() // // rowArray[currntRow] = row preArray.removeLast() } } } ///题目五:给定一个数组和一个目标数,找出数组中的不重复使用数字的和为目标值的组合 上题一样,先排序就好了,如何使用不重复,就是每次遍历的数字都从当前序号看是 func combinationSum2(_ candidates: [Int], _ target: Int) -> [[Int]] { if candidates.count == 0 { return [] } if candidates.count == 1 { if candidates[0] == target { return [candidates] }else{ return [] } } let newArray = candidates.sorted() var stack:Stack<Int> = Stack() combinationSum2Core(newArray, &stack, target,0) return resultArray } func combinationSum2Core(_ candidates: [Int],_ useArray:inout Stack<Int> , _ target: Int,_ current:Int) { if target < 0 { return } if target == 0 { resultArray.append(useArray.sequence) return } for index in current..<candidates.count { if candidates[index] > target { continue } if index > current && candidates[index] == candidates[index-1]{ continue } useArray.push(element: candidates[index]) combinationSum2Core(candidates, &useArray, target-candidates[index], index+1) useArray.pop() } } ///题目六 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合 candidates 中的数字可以无限制重复被选取。 func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] { //不用排序了 每次都重新遍历数组就好了, 从当前数字开始! if candidates.count == 0 { return [] } var stack:Stack<Int> = Stack() combinationSum(candidates, &stack, target, 0) return resultArray } func combinationSum(_ candidates: [Int],_ useArray:inout Stack<Int>,_ target: Int,_ current: Int) { if target == 0 { resultArray.append(useArray.sequence) return } if target < 0 { return } for index in current..<candidates.count { useArray.push(element: candidates[index]) combinationSum(candidates, &useArray, target-candidates[index], index) useArray.pop() } } //MARK:测试用例 /* -------------------------------------------------------------------------------------------------------------------- */ //let a = [2,3,1,0,2,5,3] //let b = [2,3,5,4,3,2,6,7] //let c:[Int] = [] //var d = Array("We are happy.") //var l1: ListNode<Int>? = ListNode(value: 1, next: nil) //let l2 = ListNode(value: 1, next: nil) //let l3 = ListNode(value: 1, next: nil) //let l4 = ListNode(value: 2, next: nil) //let l5 = ListNode(value: 3, next: nil) //let l6 = ListNode(value: 11, next: nil) //let l7 = ListNode(value: 13, next: nil) //// //l1!.pNext = l2 //l2.pNext = l3 //l3.pNext = l4 //l4.pNext = l5 //l5.pNext = l6 //l6.pNext = l7 // // //var n1: ListNode<Int>? = ListNode(value: 2, next: nil) //let n2 = ListNode(value: 4, next: nil) //let n3 = ListNode(value: 6, next: nil) //let n4 = ListNode(value: 8, next: nil) //let n5 = ListNode(value: 10, next: nil) //let n6 = ListNode(value: 12, next: nil) //let n7 = ListNode(value: 14, next: nil) // //n1!.pNext = n2 //n2.pNext = n3 //n3.pNext = n4 //n4.pNext = n5 //n5.pNext = n6 //n6.pNext = n7 // //PrintListReversingly_Recursively(pHead: l1) //let preorder = [1,2,4,7,3,5,6,8] //let inorder = [4,7,2,1,5,3,8,6] // // // //let z = Contruct(preorder: preorder, inorder: inorder) // //print(z) var a:[Int] = [2,4,5,8,9]//[17,14,13,23,22,10,5,4,3,2,1,100] ////BubbleSort(list: &a) //InsertSort(list: &a) //InsertSort1(list: &a) ////ShellSort(list: &a) //ShellSort1(list: &a) ////let z = MergeSort(list: a) ////print(z) //QuickSort(list: &a) //HeapSort(list: &a) HeapAdjust(list: &a, s: 0, m: 4) //HeapSort1(list: &a, n: 9) //AdjustHeap(list: &a, index: 0, length: 6) //BuildMaxHeap(list: &a) //print(a) //let z = Min(list: a, start: 0, end: 4) //print(z) //let a:[Character] = ["a","b","t","g","c","f","c","s","j","d","e","h"] // //let z = HasPath(list: a, rows: 3, columns: 4, matchStr: ["b","f","c","e"]) //let z1 = MaxProductAfterCutting_Solution1(length: 8) //let z2 = MaxProductAfterCutting_Solution2(length: 10) //print("\(z1),\(z2)") //let z = NumberOf1(n:0b00000111) //let z1 = NumberOf1_1(n:0b00000111) //print(z1) //print(MyPower(base: 3, exponent: 4)) //Print1ToMaxOfNDigits(n: 3) //DeleteDuplication(pHead: &l1) //let z = Match(str: ["a","a","a"], pattern: ["a","b","*","a","c","*","a"]) //print(z) //let a:[Character] = ["1","2","E","+","1",".","1"] //let b:[Character] = ["1","0"] //let c:[Character] = ["5","e","2"] //let d:[Character] = ["1",".","1",".","3"] //let e:[Character] = ["1","a","3",".","1","6"] //let z = IsNumberic(str: a) //print(z) //var a = [1,2,3,4,5] // //ReorderOddEvent(pdata: &a) //let z = FindKthToTail(pListHead: l1!, k: 0) //let z = EntryNodeOfLoop(pHead: l1!) //print(z) //var l8:ListNode<Int>? = ListNode(value: 8, next: nil) // //let z = ReverseList(pHead: &l8) //print(z) //var l8:ListNode<Int>? = nil//ListNode(value: 8, next: nil) //var n8:ListNode<Int>? = nil//ListNode(value: 8, next: nil) // //let z = Merge2(pHead1: &l1, pHead2: &n1) //print(z) //let a = BinaryTreeNode(value: 1, left: nil, right: nil) //let b = BinaryTreeNode(value: 2, left: nil, right: nil) //let c = BinaryTreeNode(value: 3, left: nil, right: nil) //let d = BinaryTreeNode(value: 4, left: nil, right: nil) //let e = BinaryTreeNode(value: 5, left: nil, right: nil) //let f = BinaryTreeNode(value: 6, left: nil, right: nil) //let g = BinaryTreeNode(value: 7, left: nil, right: nil) //let h = BinaryTreeNode(value: 8, left: nil, right: nil) //let i = BinaryTreeNode(value: 9, left: nil, right: nil) //let j = BinaryTreeNode(value: 10, left: nil, right: nil) //let k = BinaryTreeNode(value: 11, left: nil, right: nil) //let l = BinaryTreeNode(value: 12, left: nil, right: nil) //let m = BinaryTreeNode(value: 13, left: nil, right: nil) //let n = BinaryTreeNode(value: 14, left: nil, right: nil) //let o = BinaryTreeNode(value: 15, left: nil, right: nil) // //let a = BinaryTreeNode(value: 10, left: nil, right: nil) // //let b = BinaryTreeNode(value: 6, left: nil, right: nil) //let c = BinaryTreeNode(value: 14, left: nil, right: nil) // //let d = BinaryTreeNode(value: 4, left: nil, right: nil) //let e = BinaryTreeNode(value: 8, left: nil, right: nil) // //let f = BinaryTreeNode(value: 12, left: nil, right: nil) //let g = BinaryTreeNode(value: 16, left: nil, right: nil) //a.pLeft = b //a.pRight = c // //b.pLeft = d //b.pRight = e // //c.pLeft = f //c.pRight = g //let a = ComplexListNode(value: 1, pNext: nil, pSibling: nil) //let b = ComplexListNode(value: 2, pNext: nil, pSibling: nil) //let c = ComplexListNode(value: 3, pNext: nil, pSibling: nil) //let d = ComplexListNode(value: 4, pNext: nil, pSibling: nil) //let e = ComplexListNode(value: 5, pNext: nil, pSibling: nil) // //a.pNext = b //b.pNext = c //c.pNext = d //d.pNext = e // //a.pSibling = c //b.pSibling = e //e.pSibling = b // //print(CopyComplexListNode(pHead: a) as Any) // //a.pLeft = b //a.pRight = c // //b.pLeft = d //b.pRight = e // //c.pLeft = f //c.pRight = g // // //d.pLeft = h //d.pRight = i // //e.pLeft = j //e.pRight = k // //f.pLeft = l //f.pRight = m // //g.pLeft = n //g.pRight = o // // //x.pLeft = y //x.pRight = z // //let result = HasSubTree(treeA: a, treeB: x) // //print(result) //let a:[[Int]] = [] // // //let result = spiralOrder(a) //print(result) //let a = [2,1,0] //let b = [1,2,0] // //print(validateStackSequences(a, b)) //print(levelOrder(a)) //print(PrintTreeInZhi(pRoot: a)) //print(VerifySquenceOfBST(sequence: [5,7,6,9,11,10,8])) // //let s = Solution() // //print(s.pathSum(a, 22)) //print(Convert(pRootOfTree: a)) //var a:[Character] = ["a","b","c"] // //Permutation(pStr: &a) //let a = [1,2,2] //print(permuteUnique(a)) //print(subsetsWithDup(a))
true
77edeaaab7d4a3c7d65e4df714ef9e381e47814f
Swift
vtretjakov/Basketball-2021
/AR Basketball/View Controllers/ViewController.swift
UTF-8
11,872
2.5625
3
[]
no_license
// // ViewController.swift // Basketball 2021 // // Created by Владимир Третьяков // import ARKit class ViewController: UIViewController, ARSCNViewDelegate, SCNPhysicsContactDelegate { // MARK: - @IBOutlets @IBOutlet var sceneView: ARSCNView! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var stackView: UIStackView! // MARK: - Properties let configuration = ARWorldTrackingConfiguration() private var isHoopAdded = false { didSet { configuration.planeDetection = self.isHoopAdded ? [] : [.horizontal, .vertical] configuration.isLightEstimationEnabled = true sceneView.session.run(configuration, options: .removeExistingAnchors) } } var score: Int = 0 { didSet { DispatchQueue.main.async { self.scoreLabel.text = "Счёт: \(self.score)" } } } var isBallBeginContactWithRim = false var isBallEndContactWithRim = true // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() // Set the view's delegate sceneView.delegate = self sceneView.scene.physicsWorld.contactDelegate = self // Show statistics such as fps and timing information sceneView.showsStatistics = false updateUI() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Detect vertical planes configuration.planeDetection = [.horizontal, .vertical] configuration.isLightEstimationEnabled = true // Run the view's session sceneView.session.run(configuration) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Pause the view's session sceneView.session.pause() } // MARK: - Private Methods private func updateUI() { // Set padding to stackview stackView.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) stackView.isLayoutMarginsRelativeArrangement = true stackView.isHidden = true } private func getBallNode() -> SCNNode? { // Get current position to the ball guard let frame = sceneView.session.currentFrame else { return nil } // Get camera transform let cameraTransform = frame.camera.transform let matrixCameraTransform = SCNMatrix4(cameraTransform) // Ball geometry and color let ball = SCNSphere(radius: 0.125) let ballTexture: UIImage = #imageLiteral(resourceName: "basketball") ball.firstMaterial?.diffuse.contents = ballTexture // Ball node let ballNode = SCNNode(geometry: ball) ballNode.name = "ball" // Calculate force matrix for pushing the ball let power = Float(5) let x = -matrixCameraTransform.m31 * power let y = -matrixCameraTransform.m32 * power let z = -matrixCameraTransform.m33 * power let forceDirection = SCNVector3(x, y, z) // Add physics ballNode.physicsBody = SCNPhysicsBody(type: .dynamic, shape: SCNPhysicsShape(node: ballNode)) ballNode.physicsBody?.mass = 0.570 // Apply force ballNode.physicsBody?.applyForce(forceDirection, asImpulse: true) // Set parameters for ball to react with hoop and count score points ballNode.physicsBody?.categoryBitMask = BodyType.ball.rawValue ballNode.physicsBody?.collisionBitMask = BodyType.ball.rawValue | BodyType.board.rawValue | BodyType.rim.rawValue ballNode.physicsBody?.contactTestBitMask = BodyType.topPlane.rawValue | BodyType.bottomPlane.rawValue // Assign camera position to ball ballNode.simdTransform = cameraTransform return ballNode } private func getHoopNode() -> SCNNode { let scene = SCNScene(named: "Hoop.scn", inDirectory: "art.scnassets")! let hoopNode = SCNNode() let board = scene.rootNode.childNode(withName: "board", recursively: false)!.clone() let rim = scene.rootNode.childNode(withName: "rim", recursively: false)!.clone() let topPlane = scene.rootNode.childNode(withName: "top plane", recursively: false)!.clone() let bottomPlane = scene.rootNode.childNode(withName: "bottom plane", recursively: false)!.clone() board.physicsBody = SCNPhysicsBody( type: .static, shape: SCNPhysicsShape( node: board, options: [ SCNPhysicsShape.Option.type : SCNPhysicsShape.ShapeType.concavePolyhedron ] ) ) board.physicsBody?.categoryBitMask = BodyType.board.rawValue rim.physicsBody = SCNPhysicsBody( type: .static, shape: SCNPhysicsShape( node: rim, options: [ SCNPhysicsShape.Option.type : SCNPhysicsShape.ShapeType.concavePolyhedron ] ) ) rim.physicsBody?.categoryBitMask = BodyType.rim.rawValue topPlane.physicsBody = SCNPhysicsBody( type: .static, shape: SCNPhysicsShape( node: topPlane, options: [ SCNPhysicsShape.Option.type : SCNPhysicsShape.ShapeType.concavePolyhedron ] ) ) topPlane.physicsBody?.categoryBitMask = BodyType.topPlane.rawValue topPlane.physicsBody?.collisionBitMask = BodyType.ball.rawValue topPlane.opacity = 0 bottomPlane.physicsBody = SCNPhysicsBody( type: .static, shape: SCNPhysicsShape( node: bottomPlane, options: [ SCNPhysicsShape.Option.type : SCNPhysicsShape.ShapeType.concavePolyhedron ] ) ) bottomPlane.physicsBody?.categoryBitMask = BodyType.bottomPlane.rawValue bottomPlane.physicsBody?.collisionBitMask = BodyType.ball.rawValue bottomPlane.opacity = 0 hoopNode.addChildNode(board) hoopNode.addChildNode(rim) hoopNode.addChildNode(topPlane) hoopNode.addChildNode(bottomPlane) return hoopNode.clone() } private func getPlaneNode(for plane: ARPlaneAnchor) -> SCNNode { let extent = plane.extent let plane = SCNPlane(width: CGFloat(extent.x), height: CGFloat(extent.z)) plane.firstMaterial?.diffuse.contents = UIColor.blue // Create 75% transparent plane node let planeNode = SCNNode(geometry: plane) planeNode.opacity = 0.25 // Rotate plane planeNode.eulerAngles.x -= .pi / 2 return planeNode } private func updatePlaneNode(_ node: SCNNode, for anchor: ARPlaneAnchor) { guard let planeNode = node.childNodes.first, let plane = planeNode.geometry as? SCNPlane else { return } // Change plane node center planeNode.simdPosition = anchor.center // Change plane size let extent = anchor.extent plane.width = CGFloat(extent.x) plane.height = CGFloat(extent.z) } private func removeFromScene(_ node: SCNNode, fallLengh: Float) { if node.presentation.position.y < fallLengh { node.removeFromParentNode() } } private func restartGame() { isHoopAdded = false score = 0 isBallBeginContactWithRim = false isBallEndContactWithRim = true sceneView.scene.rootNode.enumerateChildNodes { (node, stop) in if node.name != nil { node.removeFromParentNode() } } stackView.isHidden = true } // MARK: - ARSCNViewDelegate func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { guard let planeAnchor = anchor as? ARPlaneAnchor, planeAnchor.alignment == .vertical else { return } // Add hoop to the center of vertical plane node.addChildNode(getPlaneNode(for: planeAnchor)) } func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) { guard let planeAnchor = anchor as? ARPlaneAnchor, planeAnchor.alignment == .vertical else { return } // Update plane node updatePlaneNode(node, for: planeAnchor) } func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) { sceneView.scene.rootNode.enumerateChildNodes { node, _ in if node.physicsBody?.categoryBitMask == BodyType.ball.rawValue { removeFromScene(node, fallLengh: -10) } } } // MARK: - PhysicsWorld func physicsWorld(_ world: SCNPhysicsWorld, didBegin contact: SCNPhysicsContact) { if !isBallBeginContactWithRim && isBallEndContactWithRim { if contact.nodeA.physicsBody?.categoryBitMask == BodyType.ball.rawValue && contact.nodeB.physicsBody?.categoryBitMask == BodyType.topPlane.rawValue { isBallBeginContactWithRim = !isBallBeginContactWithRim isBallEndContactWithRim = !isBallEndContactWithRim } } } func physicsWorld(_ world: SCNPhysicsWorld, didEnd contact: SCNPhysicsContact) { if isBallBeginContactWithRim && !isBallEndContactWithRim { if contact.nodeA.physicsBody?.categoryBitMask == BodyType.ball.rawValue && contact.nodeB.physicsBody?.categoryBitMask == BodyType.bottomPlane.rawValue { score += 1 isBallBeginContactWithRim = !isBallBeginContactWithRim isBallEndContactWithRim = !isBallEndContactWithRim } } } // MARK: - @IBActions @IBAction func userTapped(_ sender: UITapGestureRecognizer) { if isHoopAdded { guard let ballNode = getBallNode() else { return } sceneView.scene.rootNode.addChildNode(ballNode) } else { let location = sender.location(in: sceneView) guard let result = sceneView.hitTest(location, types: .existingPlaneUsingExtent).first else { return } guard let anchor = result.anchor as? ARPlaneAnchor, anchor.alignment == .vertical else { return } // Get hoop node and set it coordinates let hoopNode = getHoopNode() hoopNode.simdTransform = result.worldTransform hoopNode.eulerAngles.x -= .pi / 2 isHoopAdded = true sceneView.scene.rootNode.addChildNode(hoopNode) stackView.isHidden = false } } @IBAction func restartButtonTapped(_ sender: UIButton) { restartGame() } }
true
f155ce13deff722bf9029ac6b87af87197253bff
Swift
Saayaman/i0S
/3_TabBarController/TabBarController/TabBarController/AppDelegate.swift
UTF-8
1,798
2.703125
3
[]
no_license
// // AppDelegate.swift // TabBarController // // Created by ayako_sayama on 2017-05-29. // Copyright © 2017 ayako_sayama. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.main.bounds) //TabBar を初期化 let tabBarController = UITabBarController() //それぞれのボタンにviewコントローラをつける let favoritesVC = ViewController() favoritesVC.title = "Favorites" favoritesVC.view.backgroundColor = UIColor.orange let downloadsVC = ViewController() downloadsVC.title = "Downloads" downloadsVC.view.backgroundColor = UIColor.green let historyVC = ViewController() historyVC.title = "History" historyVC.view.backgroundColor = UIColor.yellow favoritesVC.tabBarItem = UITabBarItem(tabBarSystemItem: .favorites, tag:0) downloadsVC.tabBarItem = UITabBarItem(tabBarSystemItem: .downloads, tag:1) historyVC.tabBarItem = UITabBarItem(tabBarSystemItem: .history, tag:2) let baseControllers = [favoritesVC, downloadsVC, historyVC] tabBarController.viewControllers = baseControllers.map{UINavigationController(rootViewController: $0) } window?.rootViewController = tabBarController window?.makeKeyAndVisible() return true } //ui object gets hardware screen size }
true
fdfacc3fbd30ad879ab1f160c2b26b14395e672a
Swift
6122617139/mapbox-maps-ios
/Sources/MapboxMaps/Foundation/Extensions/Core/CoordinateBounds.swift
UTF-8
1,035
3.046875
3
[ "ISC", "BSL-1.0", "BSD-2-Clause", "MIT", "LicenseRef-scancode-object-form-exception-to-mit", "BSD-3-Clause", "Zlib" ]
permissive
import Foundation import MapboxCoreMaps // MARK: - CoordinateBounds public extension CoordinateBounds { /// The northwest coordinate of an internal `CoordinateBounds` type. var northwest: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: northeast.latitude, longitude: southwest.longitude) } /// The northwest coordinate of an internal `CoordinateBounds` type. var southeast: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: southwest.latitude, longitude: northeast.longitude) } } internal extension CoordinateBounds { func contains(_ coordinates: [CLLocationCoordinate2D]) -> Bool { let latitudeRange = southwest.latitude...northeast.latitude let longitudeRange = southwest.longitude...northeast.longitude for coordinate in coordinates { if latitudeRange.contains(coordinate.latitude) || longitudeRange.contains(coordinate.longitude) { return true } } return false } }
true
959f9d93f6a6784615f50e1c53173ad59d8f4054
Swift
soto-archive/aws-sdk-appleos-core
/Sources/AWSSDKSwiftCore/Hash.swift
UTF-8
2,983
2.515625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // Hash.swift // AWSSDKSwift // // Created by Yuki Takei on 2017/03/13. // // import Foundation #if canImport(CAWSSDKOpenSSL) import CAWSSDKOpenSSL public func sha256(_ string: String) -> [UInt8] { var bytes = Array(string.utf8) return sha256(&bytes) } public func sha256(_ bytes: inout [UInt8]) -> [UInt8] { var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) CC_SHA256(&bytes, CC_LONG(bytes.count), &hash) return hash } public func sha256(_ data: Data) -> [UInt8] { return data.withUnsafeBytes { ptr in var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) if let bytes = ptr.baseAddress?.assumingMemoryBound(to: UInt8.self) { CC_SHA256(bytes, CC_LONG(data.count), &hash) } return hash } } public func sha256(_ bytes1: inout [UInt8], _ bytes2: inout [UInt8]) -> [UInt8] { var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) var context = CC_SHA256_CTX() CC_SHA256_Init(&context) CC_SHA256_Update(&context, &bytes1, CC_LONG(bytes1.count)) CC_SHA256_Update(&context, &bytes2, CC_LONG(bytes2.count)) CC_SHA256_Final(&hash, &context) return hash } public func md5(_ data: Data) -> [UInt8] { return data.withUnsafeBytes { ptr in var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) if let bytes = ptr.baseAddress?.assumingMemoryBound(to: UInt8.self) { CC_MD5(bytes, CC_LONG(data.count), &hash) } return hash } } #elseif canImport(CommonCrypto) import CommonCrypto public func sha256(_ string: String) -> [UInt8] { var bytes = Array(string.utf8) return sha256(&bytes) } public func sha256(_ bytes: inout [UInt8]) -> [UInt8] { var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) CC_SHA256(&bytes, CC_LONG(bytes.count), &hash) return hash } public func sha256(_ data: Data) -> [UInt8] { return data.withUnsafeBytes { ptr in var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) if let bytes = ptr.baseAddress?.assumingMemoryBound(to: UInt8.self) { CC_SHA256(bytes, CC_LONG(data.count), &hash) } return hash } } public func sha256(_ bytes1: inout [UInt8], _ bytes2: inout [UInt8]) -> [UInt8] { var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) var context = CC_SHA256_CTX() CC_SHA256_Init(&context) CC_SHA256_Update(&context, &bytes1, CC_LONG(bytes1.count)) CC_SHA256_Update(&context, &bytes2, CC_LONG(bytes2.count)) CC_SHA256_Final(&hash, &context) return hash } public func md5(_ data: Data) -> [UInt8] { return data.withUnsafeBytes { ptr in var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) if let bytes = ptr.baseAddress?.assumingMemoryBound(to: UInt8.self) { CC_MD5(bytes, CC_LONG(data.count), &hash) } return hash } } #endif
true
d4ffbffbf78373270128e5d186f5b8f4ae2fb7dd
Swift
sunxcode/ecommerceApp
/ShoppingCartApp/WebServices/Webservice+SearchAPI.swift
UTF-8
3,254
2.625
3
[]
no_license
// // Webservice+SearchAPI.swift // ShoppingCartApp // // Created by Vikash Kumar on 05/07/17. // Copyright © 2017 Vikash Kumar. All rights reserved. // import Foundation typealias APIParameters = [String : Any] extension APIName { static var globalSearch = "api/Home/GlobalSearch" //GetOffers CategoryGetList static var wishCategoryAdd = "api/Customer/WishlistCategoryAdd" static var wishCategoryUpdate = "api/Customer/WishlistCategoryUpdate" static var wishCategoryDelete = "api/Customer/WishlistCategoryDelete" static var wishCategoryGet = "api/Customer/WishlistCategory" static var addProductInWishCategory = "api/Product/AddToWishList" static var cartOperations = "api/Order/OrderCartAddUpdate" //api is used to add, remove, and update item in cart, clear or empty cart. static var getCartItems = "api/Order/CartList" static var replaceCartProduct = "api/Order/CartReplaceProduct" static var getCartCountInfo = "api/Order/CartListCnt" } extension WebService { //MARK:- Search API func searchItems(params: APIParameters?, block: @escaping ResponseBlock)->URLSessionTask { return GET_REQUEST(relPath: APIName.globalSearch, param: params, block: block)!.task! } //MARK:- WishList API func addWishCategory(params: APIParameters?, block: @escaping ResponseBlock) { _ = POST_REQUEST(relPath: APIName.wishCategoryAdd, param: params, block: block) } func updateWishCategory(params: APIParameters?, block: @escaping ResponseBlock) { _ = POST_REQUEST(relPath: APIName.wishCategoryUpdate, param: params, block: block) } func deleteWishCategory(params: APIParameters?, block: @escaping ResponseBlock) { _ = POST_REQUEST(relPath: APIName.wishCategoryDelete, param: params, block: block) } func getWishListCategories(params: APIParameters?, block: @escaping ResponseBlock)->URLSessionTask { return GET_REQUEST(relPath: APIName.wishCategoryGet, param: params, block: block)!.task! } func addProductInWishCategory(params: APIParameters?, block: @escaping ResponseBlock) { _ = POST_REQUEST(relPath: APIName.addProductInWishCategory, param: params, block: block) } //MARK:- Cart API func getCartItems(params: APIParameters?, block: @escaping ResponseBlock)->URLSessionTask { return GET_REQUEST(relPath: APIName.getCartItems, param: params, block: block)!.task! } //api is used to add, remove, and update item in cart and clear cart func cartOperations(params: APIParameters, block: @escaping ResponseBlock) { _ = POST_REQUEST(relPath: APIName.cartOperations, param: params, block: block) } func replaceCartProduct(params: APIParameters, block: @escaping ResponseBlock) { _ = GET_REQUEST(relPath: APIName.replaceCartProduct, param: params, block: block) } //call this api for getting products count in cart along with product ids. func getCartProductsCountInfo(params: APIParameters?, block: @escaping ResponseBlock) { _ = GET_REQUEST(relPath: APIName.getCartCountInfo, param: params, block: block) } }
true
559f0c3f8b3496ede3f50200f940252d013df3ba
Swift
neyrpg/FoodCad
/FoodCad/viewcontroller/RemoveRefeicaoController.swift
UTF-8
996
2.96875
3
[]
no_license
// // RemoveRefeicaoController.swift // FoodCad // // Created by Ney on 28/11/17. // Copyright © 2017 Giltecnologia. All rights reserved. // import Foundation import UIKit class RemoveRefeicaoController { let controller: UIViewController init(controller: UIViewController) { self.controller = controller } func show(refeicao: Refeicao, handler: @escaping (UIAlertAction) -> Void ){ //criação de dialog let dialog = UIAlertController(title: "Felicidade", message: "A sua refeição é \(refeicao.nome). \(refeicao.detalhes()) ", preferredStyle: UIAlertControllerStyle.alert) let ok = UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil) let remove = UIAlertAction(title: "Remove", style: UIAlertActionStyle.destructive, handler: handler) dialog.addAction(ok) dialog.addAction(remove) controller.present(dialog, animated: true, completion: nil) } }
true
aed4370075d46bda01affb551aa057d14ccf29c6
Swift
ThePowerOfSwift/Celluloid
/Celluloid/SessionController+Camera.swift
UTF-8
2,551
2.734375
3
[ "MIT" ]
permissive
// // SessionController+Camera.swift // Celluloid // // Created by Alex Littlejohn on 04/10/16. // Copyright © 2016 Alex Littlejohn. All rights reserved. // import Foundation import AVFoundation public extension SessionController { /// Switch the current capture device and input with the one provided from a list of supported devices in `availableDevices` /// /// - parameter newDevice: a new AVCaptureDevice to use for video input /// /// - throws: CelluloidError.deviceConfigurationFailed public func toggle(to newDevice: AVCaptureDevice) throws { guard availableDevices.contains(newDevice) else { return } guard device != newDevice else { return } guard let oldInput = input else { throw CelluloidError.deviceConfigurationFailed } session.beginConfiguration() session.removeInput(oldInput) guard let newInput = try? AVCaptureDeviceInput(device: newDevice), session.canAddInput(newInput) else { session.addInput(oldInput) session.commitConfiguration() throw CelluloidError.deviceConfigurationFailed } session.addInput(newInput) session.commitConfiguration() input = newInput device = newDevice resetToDefaults() } public func setPointOfInterest(to point: CGPoint) throws { try configureDevice { device in let x = min(max(point.x, 0), 1) let y = min(max(point.y, 0), 1) let pointOfInterest = CGPoint(x: x, y: y) let focusMode = device.focusMode let exposureMode = device.exposureMode if focusMode != .locked && device.isFocusPointOfInterestSupported && device.isFocusModeSupported(focusMode) { device.focusPointOfInterest = pointOfInterest device.focusMode = focusMode } if exposureMode != .custom && device.isExposurePointOfInterestSupported && device.isExposureModeSupported(exposureMode) { device.exposurePointOfInterest = pointOfInterest device.exposureMode = exposureMode } } } public func setLensStabilisation(enabled: Bool) { guard let output = output, output.isLensStabilizationDuringBracketedCaptureSupported else { lensStabilizationEnabled = false return } lensStabilizationEnabled = enabled } }
true