repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
skedgo/tripkit-ios | Sources/TripKit/model/CoreData/SegmentReference+CoreDataClass.swift | 1 | 1137 | //
// SegmentReference+CoreDataClass.swift
// TripKit
//
// Created by Adrian Schönig on 12/8/21.
// Copyright © 2021 SkedGo Pty Ltd. All rights reserved.
//
//
#if canImport(CoreData)
import Foundation
import CoreData
/// A time-dependent pointer to the time-independent `SegmentTemplate`
@objc(SegmentReference)
class SegmentReference: NSManagedObject {
}
extension SegmentReference {
var template: SegmentTemplate! {
if let assigned = segmentTemplate {
return assigned
}
guard let hashCode = self.templateHashCode, let context = managedObjectContext else {
TKLog.debug("Invalid segment reference without a hash code: \(self)")
return nil
}
// link up
segmentTemplate = SegmentTemplate.fetchSegmentTemplate(withHashCode: hashCode.intValue, in: context)
return segmentTemplate
}
func assign(_ vehicle: TKVehicular?) {
vehicleUUID = vehicle?.vehicleID?.uuidString
}
func findVehicle(all: [TKVehicular]) -> TKVehicular? {
guard let uuid = vehicleUUID else { return nil }
return all.first { $0.vehicleID?.uuidString == uuid }
}
}
#endif
| apache-2.0 | bf04f1afbff94891c1ff94b3f790d423 | 22.163265 | 104 | 0.701322 | 4.157509 | false | false | false | false |
ErikOwen/Gradebook | Gradebook/ScoreTableViewController.swift | 1 | 3141 | //
// ScoreTableViewController.swift
// Gradebook
//
// Created by Erik Owen on 5/14/15.
// Copyright (c) 2015 Erik Owen. All rights reserved.
//
import Foundation
import UIKit
class ScoreTableViewCell: UITableViewCell {
var score: Score?
}
class ScoreTableViewController: UITableViewController {
var loader: GradebookLoader? {
didSet {
scores = loader!.loadScores()
var assignment: UserScore? = loader!.getCurrentAssignment()
self.title = "Scores for " + assignment!.name!
}
}
var scores: Scores? {
didSet {
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// println("view did load")
tableView.reloadData()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
// println("count for section \(section)")
if let scores = scores {
return scores.getSize()
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("scoreSubtitleCell", forIndexPath: indexPath) as! ScoreTableViewCell
let score = scores?.getScoreAtPos(indexPath.row)
cell.score = score
cell.textLabel?.text = "\(score!.score!) / \(score!.max_points!)"
cell.detailTextLabel?.text = "Letter grade received: \"\(score!.displayScore!)\""
return cell
}
// 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.
// if segue.identifier == "quakeDetails" {
// if let dest = segue.destinationViewController as? ViewController, let cell = sender as? SectionTableViewCell {
// // dest.quake = cell.quake
// }
// }
// }
}
| mit | 7288cc0f019fd301f0a8c194c0244e6a | 32.414894 | 131 | 0.627189 | 5.270134 | false | false | false | false |
groue/GRDB.swift | Tests/GRDBTests/SelectStatementTests.swift | 1 | 17698 | import XCTest
@testable import GRDB
class SelectStatementTests : GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute(sql: """
CREATE TABLE persons (
id INTEGER PRIMARY KEY,
creationDate TEXT,
name TEXT NOT NULL,
age INT)
""")
try db.execute(sql: "INSERT INTO persons (name, age) VALUES (?,?)", arguments: ["Arthur", 41])
try db.execute(sql: "INSERT INTO persons (name, age) VALUES (?,?)", arguments: ["Barbara", 26])
try db.execute(sql: "INSERT INTO persons (name, age) VALUES (?,?)", arguments: ["Craig", 13])
}
try migrator.migrate(dbWriter)
}
func testStatementCursor() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let sql = "SELECT 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 'Barbara', 'Gourde'"
let statement = try db.makeStatement(sql: sql)
let cursor = try statement.makeCursor()
// Test that cursor provides statement information
XCTAssertEqual(cursor.sql, sql)
XCTAssertEqual(cursor.arguments, [])
XCTAssertEqual(cursor.columnCount, 2)
XCTAssertEqual(cursor.columnNames, ["firstName", "lastName"])
XCTAssertEqual(cursor.databaseRegion.description, "empty")
XCTAssertFalse(try cursor.next() == nil)
XCTAssertFalse(try cursor.next() == nil)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
}
func testStatementCursorStepFailure() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let customError = NSError(domain: "Custom", code: 0xDEAD)
db.add(function: DatabaseFunction("throw", argumentCount: 0, pure: true) { _ in throw customError })
func test(_ cursor: StatementCursor) throws {
let sql = cursor.sql
do {
_ = try cursor.next()
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, "\(customError)")
XCTAssertEqual(error.sql!, sql)
XCTAssertEqual(error.description, "SQLite error 1: \(customError) - while executing `\(sql)`")
}
do {
_ = try cursor.next()
XCTFail()
} catch is DatabaseError {
// Various SQLite and SQLCipher versions don't emit the same
// error. What we care about is that there is an error.
}
}
try test(db.makeStatement(sql: "SELECT throw(), NULL").makeCursor())
try test(db.makeStatement(sql: "SELECT 0, throw(), NULL").makeCursor())
}
}
func testArrayStatementArguments() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < ?")
let ages = [20, 30, 40, 50]
let counts = try ages.map { try Int.fetchOne(statement, arguments: [$0])! }
XCTAssertEqual(counts, [1,2,2,3])
}
}
func testStatementArgumentsSetterWithArray() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < ?")
let ages = [20, 30, 40, 50]
let counts = try ages.map { (age: Int) -> Int in
statement.arguments = [age]
return try Int.fetchOne(statement)!
}
XCTAssertEqual(counts, [1,2,2,3])
}
}
func testDictionaryStatementArguments() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < :age")
let ageDicts: [[String: DatabaseValueConvertible?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]]
let counts = try ageDicts.map { dic -> Int in
// Make sure we don't trigger a failible initializer
let arguments: StatementArguments = StatementArguments(dic)
return try Int.fetchOne(statement, arguments: arguments)!
}
XCTAssertEqual(counts, [1,2,2,3])
}
}
func testStatementArgumentsSetterWithDictionary() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < :age")
let ageDicts: [[String: DatabaseValueConvertible?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]]
let counts = try ageDicts.map { ageDict -> Int in
statement.arguments = StatementArguments(ageDict)
return try Int.fetchOne(statement)!
}
XCTAssertEqual(counts, [1,2,2,3])
}
}
func testDatabaseErrorThrownBySelectStatementContainSQL() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
_ = try db.makeStatement(sql: "SELECT * FROM blah")
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message!, "no such table: blah")
XCTAssertEqual(error.sql!, "SELECT * FROM blah")
XCTAssertEqual(error.description, "SQLite error 1: no such table: blah - while executing `SELECT * FROM blah`")
}
}
}
func testCachedSelectStatementStepFailure() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var needsThrow = false
db.add(function: DatabaseFunction("bomb", argumentCount: 0, pure: false) { _ in
if needsThrow {
throw DatabaseError(message: "boom")
}
return "success"
})
let sql = "SELECT bomb()"
needsThrow = false
XCTAssertEqual(try String.fetchAll(db.cachedStatement(sql: sql)), ["success"])
do {
needsThrow = true
_ = try String.fetchAll(db.cachedStatement(sql: sql))
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message!, "boom")
XCTAssertEqual(error.sql!, sql)
XCTAssertEqual(error.description, "SQLite error 1: boom - while executing `\(sql)`")
}
needsThrow = false
XCTAssertEqual(try String.fetchAll(db.cachedStatement(sql: sql)), ["success"])
}
}
func testConsumeMultipleStatements() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.writeWithoutTransaction { db in
do {
// SQL, no argument
let statements = try db.allStatements(sql: """
SELECT age FROM persons ORDER BY age;
SELECT age FROM persons ORDER BY age DESC;
""")
let ages = try Array(statements.flatMap { try Int.fetchCursor($0) })
XCTAssertEqual(ages, [13, 26, 41, 41, 26, 13])
}
do {
// Literal, no argument
let statements = try db.allStatements(literal: """
SELECT age FROM persons ORDER BY age;
SELECT age FROM persons ORDER BY age DESC;
""")
let ages = try Array(statements.flatMap { try Int.fetchCursor($0) })
XCTAssertEqual(ages, [13, 26, 41, 41, 26, 13])
}
do {
// SQL, missing arguments
let statements = try db.allStatements(sql: """
SELECT count(*) FROM persons WHERE age > ?;
SELECT count(*) FROM persons WHERE age < ?;
""")
let counts = try Array(statements.map { try
Int.fetchOne($0, arguments: [30])!
})
XCTAssertEqual(counts, [1, 2])
}
do {
// Literal, missing arguments
let statements = try db.allStatements(literal: """
SELECT count(*) FROM persons WHERE age > ?;
SELECT count(*) FROM persons WHERE age < ?;
""")
let counts = try Array(statements.map { try
Int.fetchOne($0, arguments: [30])!
})
XCTAssertEqual(counts, [1, 2])
}
do {
// SQL, matching arguments
let statements = try db.allStatements(sql: """
SELECT name FROM persons WHERE name = ?;
SELECT name FROM persons WHERE age > ? ORDER BY name;
""", arguments: ["Arthur", 20])
let names = try Array(statements.map { try String.fetchAll($0) })
XCTAssertEqual(names, [["Arthur"], ["Arthur", "Barbara"]])
}
do {
// Literal, matching arguments
let statements = try db.allStatements(literal: """
SELECT name FROM persons WHERE name = \("Arthur");
SELECT name FROM persons WHERE age > \(20) ORDER BY name;
""")
let names = try Array(statements.map { try String.fetchAll($0) })
XCTAssertEqual(names, [["Arthur"], ["Arthur", "Barbara"]])
}
do {
// SQL, too few arguments
let statements = try db.allStatements(sql: """
SELECT name FROM persons WHERE name = ?;
SELECT name FROM persons WHERE age > ? ORDER BY name;
""", arguments: ["Arthur"])
_ = try Array(statements.map { try String.fetchAll($0) })
XCTFail("Expected Error")
} catch DatabaseError.SQLITE_MISUSE {
// OK
}
do {
// Literal, too few arguments
let statements = try db.allStatements(literal: """
SELECT name FROM persons WHERE name = \("Arthur");
SELECT name FROM persons WHERE age > ? ORDER BY name;
""")
_ = try Array(statements.map { try String.fetchAll($0) })
XCTFail("Expected Error")
} catch DatabaseError.SQLITE_MISUSE {
// OK
}
do {
// SQL, too many arguments
let statements = try db.allStatements(sql: """
SELECT name FROM persons WHERE name = ?;
SELECT name FROM persons WHERE age > ? ORDER BY name;
""", arguments: ["Arthur", 20, 55])
_ = try Array(statements.map { try String.fetchAll($0) })
XCTFail("Expected Error")
} catch DatabaseError.SQLITE_MISUSE {
// OK
}
do {
// Mix statement kinds
let statements = try db.allStatements(literal: """
CREATE TABLE t(a);
INSERT INTO t VALUES (0);
SELECT a FROM t ORDER BY a;
INSERT INTO t VALUES (1);
SELECT a FROM t ORDER BY a;
""")
let values = try Array(statements.map { try Int.fetchAll($0) })
XCTAssertEqual(values, [[], [], [0], [], [0, 1]])
}
}
}
func testRegion() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.writeWithoutTransaction { db in
class Observer: TransactionObserver {
private var didChange = false
var triggered = false
let region: DatabaseRegion
init(region: DatabaseRegion) {
self.region = region
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
region.isModified(byEventsOfKind: eventKind)
}
func databaseDidChange(with event: DatabaseEvent) {
didChange = true
}
func databaseDidCommit(_ db: Database) {
triggered = didChange
didChange = false
}
func databaseDidRollback(_ db: Database) {
didChange = false
}
}
try db.create(table: "table1") { t in
t.column("id", .integer).primaryKey()
t.column("id3", .integer).references("table3", column: "id", onDelete: .cascade, onUpdate: .cascade)
t.column("id4", .integer).references("table4", column: "id", onDelete: .setNull, onUpdate: .cascade)
t.column("a", .integer)
t.column("b", .integer)
}
try db.create(table: "table2") { t in
t.column("id", .integer).primaryKey()
t.column("a", .integer)
t.column("b", .integer)
}
try db.create(table: "table3") { t in
t.column("id", .integer).primaryKey()
}
try db.create(table: "table4") { t in
t.column("id", .integer).primaryKey()
}
try db.create(table: "table5") { t in
t.column("id", .integer).primaryKey()
}
try db.execute(sql: "CREATE TRIGGER table5trigger AFTER INSERT ON table5 BEGIN INSERT INTO table1 (id3, id4, a, b) VALUES (NULL, NULL, 0, 0); END")
let statements = try [
db.makeStatement(sql: "SELECT * FROM table1"),
db.makeStatement(sql: "SELECT id, id3, a FROM table1"),
db.makeStatement(sql: "SELECT table1.id, table1.a, table2.a FROM table1 JOIN table2 ON table1.id = table2.id"),
db.makeStatement(sql: "SELECT COUNT(*) FROM table1"),
]
let observers = statements.map { Observer(region: $0.databaseRegion) }
XCTAssertEqual(observers.map { $0.region.description }, ["table1(a,b,id,id3,id4)","table1(a,id,id3)", "table1(a,id),table2(a,id)", "table1(*)"])
for observer in observers {
db.add(transactionObserver: observer)
}
try db.execute(sql: "INSERT INTO table3 (id) VALUES (1)")
try db.execute(sql: "INSERT INTO table4 (id) VALUES (1)")
try db.execute(sql: "INSERT INTO table1 (id, a, b, id3, id4) VALUES (NULL, 0, 0, 1, 1)")
XCTAssertEqual(observers.map(\.triggered), [true, true, true, true])
try db.execute(sql: "INSERT INTO table2 (id, a, b) VALUES (NULL, 0, 0)")
XCTAssertEqual(observers.map(\.triggered), [false, false, true, false])
try db.execute(sql: "UPDATE table1 SET a = 1")
XCTAssertEqual(observers.map(\.triggered), [true, true, true, true])
try db.execute(sql: "UPDATE table1 SET b = 1")
XCTAssertEqual(observers.map(\.triggered), [true, false, false, true])
try db.execute(sql: "UPDATE table2 SET a = 1")
XCTAssertEqual(observers.map(\.triggered), [false, false, true, false])
try db.execute(sql: "UPDATE table2 SET b = 1")
XCTAssertEqual(observers.map(\.triggered), [false, false, false, false])
try db.execute(sql: "UPDATE table3 SET id = 2 WHERE id = 1")
XCTAssertEqual(observers.map(\.triggered), [true, true, false, true])
try db.execute(sql: "UPDATE table4 SET id = 2 WHERE id = 1")
XCTAssertEqual(observers.map(\.triggered), [true, false, false, true])
try db.execute(sql: "DELETE FROM table4")
XCTAssertEqual(observers.map(\.triggered), [true, false, false, true])
try db.execute(sql: "INSERT INTO table4 (id) VALUES (1)")
try db.execute(sql: "DELETE FROM table4")
XCTAssertEqual(observers.map(\.triggered), [false, false, false, false])
try db.execute(sql: "DELETE FROM table3")
XCTAssertEqual(observers.map(\.triggered), [true, true, true, true])
try db.execute(sql: "INSERT INTO table5 (id) VALUES (NULL)")
XCTAssertEqual(observers.map(\.triggered), [true, true, true, true])
}
}
}
| mit | 82ac1cf5665f40993af108668bc46f96 | 44.263427 | 159 | 0.511131 | 5.01644 | false | false | false | false |
andrea-prearo/SwiftExamples | CoreDataCodable/CoreDataCodable/MainViewController.swift | 1 | 2556 | //
// ViewController.swift
// CoreDataCodable
//
// Created by Andrea Prearo on 3/29/18.
// Copyright © 2018 Andrea Prearo. All rights reserved.
//
import UIKit
import CoreData
class MainViewController: UITableViewController {
private static let UserCellReuseId = "UserCell"
private var userController: UserController?
public static func create(persistentContainer: NSPersistentContainer, coreDataWrapper: CoreDataWrapper) -> MainViewController {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mainViewController = storyboard.instantiateViewController(withIdentifier: "MainViewController") as! MainViewController
let userController = UserController(persistentContainer: persistentContainer, coreDataWrapper: coreDataWrapper)
mainViewController.userController = userController
return mainViewController
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: MainViewController.UserCellReuseId)
tableView.allowsSelection = false
userController?.fetchItems { [weak self] (success, error) in
guard let strongSelf = self else { return }
if !success {
DispatchQueue.main.async {
let title = "Error"
if let error = error {
strongSelf.showError(title, message: error.localizedDescription)
} else {
strongSelf.showError(title, message: NSLocalizedString("Can't retrieve contacts.", comment: "Can't retrieve contacts."))
}
}
} else {
DispatchQueue.main.async {
strongSelf.tableView.reloadData()
}
}
}
}
}
// MARK: UITableViewDataSource
extension MainViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userController?.itemCount ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MainViewController.UserCellReuseId, for: indexPath)
if let viewModel = userController?.item(at: indexPath.row) {
cell.textLabel?.text = "\(viewModel.username) - \(viewModel.role) (#\(indexPath.row))"
} else {
cell.textLabel?.text = "???"
}
return cell
}
}
| mit | e8dc0f2bf408fe860ebd9da13868d38a | 36.028986 | 144 | 0.648924 | 5.741573 | false | false | false | false |
Shvier/Dota2Helper | Dota2Helper/Dota2Helper/Base/Controller/DHBaseViewController.swift | 1 | 1999 | //
// DHBaseViewController.swift
// Dota2Helper
//
// Created by Shvier on 10/19/16.
// Copyright © 2016 Shvier. All rights reserved.
//
import UIKit
import Reachability
class DHBaseViewController: UIViewController {
lazy var reachability: Reachability = {
return Reachability()
}()!
@objc func reachabilityChanged(note: NSNotification) {
}
func setNaviAndTabStatus(isHidden: Bool) {
self.navigationController?.setNavigationBarHidden(isHidden, animated: true)
self.hidesBottomBarWhenPushed = isHidden
self.tabBarController?.tabBar.isHidden = isHidden
}
func setView() {
view.backgroundColor = UIColor.white
self.navigationController?.navigationBar.isTranslucent = false
self.tabBarController?.tabBar.isTranslucent = false
navigationController?.navigationBar.barTintColor = UIColor.black
navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: kTabBarItemColor]
navigationItem.title = "掌刀"
self.automaticallyAdjustsScrollViewInsets = false
}
override func viewDidLoad() {
super.viewDidLoad()
setView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged),name: Notification.Name.reachabilityChanged,object: reachability)
do {
try reachability.startNotifier()
} catch {
DHLog("could not start reachability notifier")
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
reachability.stopNotifier()
NotificationCenter.default.removeObserver(self, name: Notification.Name.reachabilityChanged, object: reachability)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| apache-2.0 | 7c221a1378a80d3e1eb7583902d2858c | 30.650794 | 164 | 0.694082 | 5.554318 | false | false | false | false |
cornerAnt/PilesSugar | PilesSugar/PilesSugar/Module/Club/ClubHot/Model/ClubHotModel.swift | 1 | 3913 | //
// ClubHotModel.swift
// PilesSugar
//
// Created by SoloKM on 16/1/13.
// Copyright © 2016年 SoloKM. All rights reserved.
//
import UIKit
import SwiftyJSON
private let comment_countWidth : CGFloat = 25.0
private let avatarWidth : CGFloat = 100.0
class ClubHotModel: NSObject {
var id :Int!
var path: String!
var comment_count:Int!
var visit_count:Int!
var content:String!
var avatar:String!
var name:String!
var username:String!
var active_time:Int!
var add_datetime_ts:Int!
// 最终cell的高度
var modelHeight:CGFloat!{
var finalHeight: CGFloat = kCommenMargin
// 1.计算文章高度
let contentWidth = kMainScreenW - comment_countWidth - 5 * kCommenMargin
let contentHeight = content!.getTextRectSize(UIFont.systemFontOfSize(10), size: CGSize(width: contentWidth, height: 300)).height
finalHeight += contentHeight + kCommenMargin
// 2.计算图片高度
if path.isEmpty {
finalHeight += kCommenMargin
}else{
finalHeight += avatarWidth + kCommenMargin
}
// 3.计算用户信息高度
let userInfoHeight = name!.getTextRectSize(UIFont.systemFontOfSize(9), size: CGSize(width: contentWidth, height: 200)).height
finalHeight += kCommenMargin + userInfoHeight
return finalHeight
}
//
// override init() {
// super.init()
//
// comment_count = 0
// content = ""
// avatar = ""
// name = ""
// username = ""
// active_time = 0
// add_datetime_ts = 0
// path = ""
//
//
// }
class func loadCulbHotModels(data:NSData) -> [ClubHotModel]{
let json = JSON(data: data)
var clubHotModels = [ClubHotModel]()
for (_,subJson):(String, JSON) in json["data"]["object_list"]{
let clubHotModel = ClubHotModel()
clubHotModel.id = subJson["id"].intValue
clubHotModel.path = subJson["photos"][0]["path"].stringValue
clubHotModel.comment_count = subJson["comment_count"].intValue
clubHotModel.visit_count = subJson["visit_count"].intValue
clubHotModel.active_time = subJson["active_time"].intValue
clubHotModel.add_datetime_ts = subJson["add_datetime_ts"].intValue
clubHotModel.name = subJson["club"]["name"].stringValue
clubHotModel.content = subJson["content"].stringValue
clubHotModel.avatar = subJson["sender"]["avatar"].stringValue
clubHotModel.username = subJson["sender"]["username"].stringValue
clubHotModels.append(clubHotModel)
}
return clubHotModels
}
// "id": 117792,
// "content": "讲一个暗恋的故事吧! 我先来",
// "category": "default",
// "sender": {
// "id": 10267604,
// "username": "萧潇肖筱",
// "avatar": "http://cdn.duitang.com/uploads/people/201512/20/20151220213752_SCyNG.jpeg"
// },
// "photos": [{
// "width": 1200,
// "height": 2133,
// "path": "http://img5.duitang.com/uploads/item/201510/06/20151006183742_NrM8Y.jpeg"
// }],
// "tags": [{
// "id": 89567,
// "name": "精选",
// "relation_type": 2
// }],
// "comment_count": 1542,
// "visit_count": 0,
// "active_time": 1452652967,
// "add_datetime_ts": 1444127862,
// "club": {
// "id": "54aa79de17c2196560f068a4",
// "name": "暗恋互助会"
// }
}
| apache-2.0 | 7a3e52ad705cd27daf7a7d7960b2ba0c | 26.035461 | 136 | 0.524921 | 3.897751 | false | false | false | false |
apple/swift-driver | Sources/SwiftDriver/ExplicitModuleBuilds/SerializableModuleArtifacts.swift | 1 | 3309 | //===--------------- SwiftModuleArtifacts.swift ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Describes a given Swift module's pre-built module artifacts:
/// - Swift Module (name)
/// - Swift Module Path
/// - Swift Doc Path
/// - Swift Source Info Path
@_spi(Testing) public struct SwiftModuleArtifactInfo: Codable {
/// The module's name
public let moduleName: String
/// The path for the module's .swiftmodule file
public let modulePath: TextualVirtualPath
/// The path for the module's .swiftdoc file
public let docPath: TextualVirtualPath?
/// The path for the module's .swiftsourceinfo file
public let sourceInfoPath: TextualVirtualPath?
/// A flag to indicate whether this module is a framework
public let isFramework: Bool
init(name: String, modulePath: TextualVirtualPath, docPath: TextualVirtualPath? = nil,
sourceInfoPath: TextualVirtualPath? = nil, isFramework: Bool = false) {
self.moduleName = name
self.modulePath = modulePath
self.docPath = docPath
self.sourceInfoPath = sourceInfoPath
self.isFramework = isFramework
}
}
/// Describes a given Clang module's pre-built module artifacts:
/// - Clang Module (name)
/// - Clang Module (PCM) Path
/// - Clang Module Map Path
@_spi(Testing) public struct ClangModuleArtifactInfo: Codable {
/// The module's name
public let moduleName: String
/// The path for the module's .pcm file
public let modulePath: TextualVirtualPath
/// The path for this module's .modulemap file
public let moduleMapPath: TextualVirtualPath
init(name: String, modulePath: TextualVirtualPath, moduleMapPath: TextualVirtualPath) {
self.moduleName = name
self.modulePath = modulePath
self.moduleMapPath = moduleMapPath
}
}
/// Describes a given module's batch dependency scanning input info
/// - Module Name
/// - Extra PCM build arguments (for Clang modules only)
/// - Dependency graph output path
public enum BatchScanModuleInfo: Encodable {
case swift(BatchScanSwiftModuleInfo)
case clang(BatchScanClangModuleInfo)
}
public struct BatchScanSwiftModuleInfo: Encodable {
var swiftModuleName: String
var output: String
init(moduleName: String, outputPath: String) {
self.swiftModuleName = moduleName
self.output = outputPath
}
}
public struct BatchScanClangModuleInfo: Encodable {
var clangModuleName: String
var arguments: String
var output: String
init(moduleName: String, pcmArgs: String, outputPath: String) {
self.clangModuleName = moduleName
self.arguments = pcmArgs
self.output = outputPath
}
}
public extension BatchScanModuleInfo {
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .swift(let swiftInfo):
try container.encode(swiftInfo)
case .clang(let clangInfo):
try container.encode(clangInfo)
}
}
}
| apache-2.0 | ca3df71f2f85418a60d84bbb81c2fca2 | 32.09 | 89 | 0.704442 | 4.576763 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureSettings/Sources/FeatureSettingsUI/AnalyticsEvents/NewAnalyticsEvents+Settings.swift | 1 | 1282 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
extension AnalyticsEvents.New {
enum Settings: AnalyticsEvent {
var type: AnalyticsEventType { .nabu }
case addMobileNumberClicked(origin: Origin)
case changeMobileNumberClicked
case notificationClicked
case deleteAccountClicked(origin: String)
case walletReferralProgramClicked(origin: String)
case notificationPreferencesUpdated(emailEnabled: Bool?, smsEnabled: Bool?)
case settingsCurrencyClicked(currency: String)
case settingsTradingCurrencyClicked(currency: String)
case settingsHyperlinkClicked(destination: Destination)
enum Destination: String, StringRawRepresentable {
case about = "ABOUT"
case cookiesPolicy = "COOKIES_POLICY"
case privacyPolicy = "PRIVACY_POLICY"
case rateUs = "RATE_US"
case termsOfService = "TERMS_OF_SERVICE"
}
enum Origin: String, StringRawRepresentable {
case settings = "SETTINGS"
}
enum ReferralOrigin: String, StringRawRepresentable {
case profile
case portfolio
case popupsheet
case deeplink
}
}
}
| lgpl-3.0 | b982c1c640924eff58c412b41548bf1f | 32.710526 | 83 | 0.655738 | 5.3375 | false | false | false | false |
ollie-williams/octopus | main.swift | 1 | 4309 | import Darwin
func lnprint<T>(val:T, file: String = __FILE__, line: Int = __LINE__) -> Void {
print("\(file)(\(line)): \(val)")
}
func parse<T:Parser>(parser:T, string:String) -> T.Target? {
let stream = CharStream(str:string)
return parser.parse(stream)
}
let json_input = try! String(contentsOfFile: "test.json")
print(json_input)
let json = JSParser.parse(json_input)
print(json!)
import Cocoa
func readline() -> String {
let keyboard = NSFileHandle.fileHandleWithStandardInput()
let inputData = keyboard.availableData
return NSString(data: inputData, encoding:NSUTF8StringEncoding)! as String
}
func mainloop() -> Void {
let calcp = Calculator() ~> eof()
while(true) {
print("> ")
fflush(__stdoutp)
let s = readline()
let stream = CharStream(str:s)
if stream.startsWith("quit") || stream.startsWith("exit") {
return
}
if let result = calcp.parse(stream) {
print(result)
} else {
print("syntax error")
}
}
}
mainloop()
// Identifiers
//let identifier = regex("[_a-zA-Z][_a-zA-Z0-9]*") ~> skip
/*
func parse<T:Parser>(parser:T, string:String) -> T.Target? {
var stream = CharStream(str:string)
return parser.parse(stream)
}
class Expr {
let symbol : String
let children: [Expr]
init(symbol:String, children:[Expr]) {
self.symbol = symbol
self.children = children
}
class func MakeFn(symbol:String, children:[Expr]) -> Expr {
return Expr(symbol:symbol, children:children)
}
class func MakeLeaf(symbol:String) -> Expr {
return Expr(symbol:symbol, children:[])
}
}
func cStyle(expr:Expr) -> String {
if expr.children.count == 0 {
return expr.symbol
}
var args = cStyle(expr.children[0])
for i in 1..<expr.children.count {
args = args + ", " + cStyle(expr.children[i])
}
return "\(expr.symbol)(\(args))"
}
let skip = manychars(const(" "))
func idChar(c:Character) -> Bool {
switch c {
case "(", ")", " ", "!", "?", "+", "*", ",":
return false
default:
return true
}
}
let identifier = many1chars(satisfy(idChar)) ~> skip
let leaf = identifier |> Expr.MakeLeaf
class ExprOp {
let symb:String
init(_ symb:String) {
self.symb = symb
}
func binary(left:Expr, _ right:Expr) -> Expr {
return Expr.MakeFn(symb, children:[left, right])
}
func unary(arg:Expr) -> Expr {
return Expr.MakeFn(symb, children:[arg])
}
}
let opFormat = (regex("[+*!?-]")) ~> skip
let opp = OperatorPrecedence<Expr>(opFormat.parse)
opp.addOperator("+", .LeftInfix(ExprOp("+").binary, 60))
opp.addOperator("-", .LeftInfix(ExprOp("-").binary, 60))
opp.addOperator("*", .RightInfix(ExprOp("*").binary, 70))
opp.addPrefix("!", Prefix(ExprOp("!").unary, 200))
opp.addPrefix("?", Prefix(ExprOp("?").unary, 50))
opp.addPrefix("-", Prefix(ExprOp("-").unary, 200))
opp.addPrefix("+", Prefix(ExprOp("+").unary, 200))
let oparen = const("(") ~> skip
let cparen = const(")") ~> skip
let comma = const(",") ~> skip
let brackets = oparen >~ opp ~> cparen
let fncall = identifier ~>~ (oparen >~ sepby(opp, comma) ~> cparen) |> Expr.MakeFn
let flt = FloatParser(strict:false) ~> skip
lnprint(parse(flt, "-123"))
lnprint(parse(flt, "12.3"))
lnprint(parse(flt, "0.123"))
lnprint(parse(flt, "-.123"))
lnprint(parse(flt, "-12.3e39"))
let number = flt |> {(x:Double)->Expr in Expr.MakeLeaf("\(x)")}
let termParser = fncall | brackets | number | leaf
opp.term = termParser.parse
lnprint(cStyle(parse(opp, "foo")!))
lnprint(cStyle(parse(opp, "foo + bar")!))
lnprint(cStyle(parse(opp, "foo + bar + abc")!))
lnprint(cStyle(parse(opp, "foo * bar + abc")!))
lnprint(cStyle(parse(opp, "22.3 + foo * abc")!))
lnprint(cStyle(parse(opp, "foo * abc + 43.79e3")!))
lnprint(cStyle(parse(opp, "foo + !43.79e3 * abc")!))
lnprint(cStyle(parse(opp, "22.3 + foo * abc")!))
lnprint(cStyle(parse(opp, "foo * (bar + abc)")!))
lnprint(cStyle(parse(opp, "foo * bar * abc")!))
lnprint(cStyle(parse(opp, "!foo")!))
lnprint(cStyle(parse(opp, "!?foo")!))
lnprint(cStyle(parse(opp, "!foo + bar")!))
lnprint(cStyle(parse(opp, "!(foo + bar)")!))
lnprint(cStyle(parse(opp, "?foo + bar")!))
lnprint(cStyle(parse(opp, "sqrt(a + b)")!))
lnprint(cStyle(parse(opp, "goo(a + b, c * sqrt(d))")!))
lnprint(cStyle(parse(opp, "foo - -bar")!))
lnprint(cStyle(parse(opp, "foo - -22.9")!))
*/
| apache-2.0 | d9d5c07624c6100f832f86930e04b650 | 24.497041 | 82 | 0.627988 | 3.080057 | false | false | false | false |
huonw/swift | stdlib/public/SDK/Intents/INSearchForPhotosIntentResponse.swift | 42 | 885 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Intents
import Foundation
#if os(iOS) || os(watchOS)
@available(iOS 10.0, watchOS 3.2, *)
extension INSearchForPhotosIntentResponse {
@nonobjc
public final var searchResultsCount: Int? {
get {
return __searchResultsCount?.intValue
}
set {
__searchResultsCount = newValue.map { NSNumber(value: $0) }
}
}
}
#endif
| apache-2.0 | 142c42ed15f07b83081e5b7415a69a05 | 29.517241 | 80 | 0.577401 | 4.657895 | false | false | false | false |
heshamsalman/OctoViewer | Pods/ReusableViews/ReusableViews/Classes/UITableViewExtensions.swift | 1 | 3098 | //
// UITableViewExtensions.swift
// ReusableViews
//
// Created by Hesham Salman on 5/11/17.
//
//
import Foundation
public extension UITableView {
/// Register a cell whose reuse identifier is the same as its class name
///
/// - Parameter _: UITableViewCell
public func register<Cell: UITableViewCell>(_: Cell.Type) where Cell: ReusableView {
register(Cell.self, forCellReuseIdentifier: Cell.defaultReuseIdentifier)
}
/// Register a header footer view whose reuse identifier is the same as its class name
///
/// - Parameter _: UIHeaderFooterView
public func register<View: UITableViewHeaderFooterView>(_: View.Type) where View: ReusableView {
register(View.self, forHeaderFooterViewReuseIdentifier: View.defaultReuseIdentifier)
}
/// Register a cell from a nib whose reuse identifier and nib name is the same as its class name
///
/// - Parameter _: UITableViewCell
public func register<Cell: UITableViewCell>(_: Cell.Type)
where Cell: ReusableView, Cell: NibLoadableView {
let bundle = Bundle(for: Cell.self)
let nib = UINib(nibName: Cell.nibName, bundle: bundle)
register(nib, forCellReuseIdentifier: Cell.defaultReuseIdentifier)
}
/// Register a reusable header footer view whose reuse identifier and
/// nib name is the same as its class name
///
/// - Parameter _: UIHeaderFooterView
public func register<View: UITableViewHeaderFooterView>(_: View.Type)
where View: ReusableView, View: NibLoadableView {
let bundle = Bundle(for: View.self)
let nib = UINib(nibName: View.nibName, bundle: bundle)
register(nib, forHeaderFooterViewReuseIdentifier: View.defaultReuseIdentifier)
}
/// Dequeues a reusable cell whose reuse identifier is the same as its class name
///
/// Does not require banging the `as` since that's already implicitly handled by this method.
/// Usage example:
/// tableView.dequeueReusableCell(for: indexPath) as MyTableViewCellType
///
/// - Parameter indexPath: indexPath for cell
/// - Returns: UITableViewCell
public func dequeueReusableCell<Cell: UITableViewCell>(for indexPath: IndexPath) -> Cell
where Cell: ReusableView {
guard let cell = dequeueReusableCell(withIdentifier: Cell.defaultReuseIdentifier, for: indexPath) as? Cell else {
fatalError("Could not dequeue cell with identifier: \(Cell.defaultReuseIdentifier)")
}
return cell
}
/// Dequeues a reusable header footer view whose reuse identifier is the same as its class name
///
/// Does not require banging the 'as' since that's implicitly handled by this method.
///
/// - Parameter section: Int for section
/// - Returns: UITableViewHeaderFooterView
public func dequeueReusableHeaderFooterView<View: UITableViewHeaderFooterView>(inSection section: Int) -> View
where View: ReusableView {
guard let view = dequeueReusableHeaderFooterView(withIdentifier: View.defaultReuseIdentifier) as? View else {
fatalError("Could not dequeue cell with identifier: \(View.defaultReuseIdentifier)")
}
return view
}
}
| apache-2.0 | 8361f38a1cf9f6a255327ee7c9dccb8c | 38.717949 | 119 | 0.725629 | 5.053834 | false | false | false | false |
hpux735/PMJSON | Tests/JSONDecoderTests.swift | 1 | 23539 | //
// JSONDecoderTests.swift
// JSONTests
//
// Created by Kevin Ballard on 10/8/15.
// Copyright © 2016 Postmates.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
import XCTest
import PMJSON
#if os(iOS) || os(OSX) || os(watchOS) || os(tvOS)
import struct Foundation.Decimal
#endif
let bigJson: Data = {
var s = "[\n"
for _ in 0..<1000 {
s += "{ \"a\": true, \"b\": null, \"c\":3.1415, \"d\": \"Hello world\", \"e\": [1,2,3]},"
}
s += "{}]"
return s.data(using: String.Encoding.utf8)!
}()
private func readFixture(_ name: String, withExtension ext: String?) throws -> Data {
struct NoSuchFixture: Error {}
guard let url = Bundle(for: JSONDecoderTests.self).url(forResource: name, withExtension: ext) else {
throw NoSuchFixture()
}
return try Data(contentsOf: url)
}
class JSONDecoderTests: XCTestCase {
func testBasic() {
assertMatchesJSON(try JSON.decode("42"), 42)
assertMatchesJSON(try JSON.decode("\"hello\""), "hello")
assertMatchesJSON(try JSON.decode("null"), nil)
assertMatchesJSON(try JSON.decode("[true, false]"), [true, false])
assertMatchesJSON(try JSON.decode("[1, 2, 3]"), [1, 2, 3])
assertMatchesJSON(try JSON.decode("{\"one\": 1, \"two\": 2, \"three\": 3}"), ["one": 1, "two": 2, "three": 3])
assertMatchesJSON(try JSON.decode("[1.23, 4e7]"), [1.23, 4e7])
#if os(iOS) || os(OSX) || os(watchOS) || os(tvOS)
assertMatchesJSON(try JSON.decode("[1.23, 4e7]", options: [.useDecimals]), [JSON(1.23 as Decimal), JSON(4e7 as Decimal)])
#endif
}
func testDouble() {
XCTAssertEqual(try JSON.decode("-5.4272823085455e-05"), -5.4272823085455e-05)
XCTAssertEqual(try JSON.decode("-5.4272823085455e+05"), -5.4272823085455e+05)
#if os(iOS) || os(OSX) || os(watchOS) || os(tvOS)
XCTAssertEqual(try JSON.decode("-5.4272823085455e+05", options: [.useDecimals]), JSON(Decimal(string: "-5.4272823085455e+05")!))
#endif
}
func testStringEscapes() {
assertMatchesJSON(try JSON.decode("\" \\\\\\\"\\/\\b\\f\\n\\r\\t \""), " \\\"/\u{8}\u{C}\n\r\t ")
assertMatchesJSON(try JSON.decode("\" \\u200D\\u00A9\\uFFFD \""), " \u{200D}©\u{FFFD} ")
}
func testSurrogatePair() {
assertMatchesJSON(try JSON.decode("\"emoji fun: 💩\\uD83D\\uDCA9\""), "emoji fun: 💩💩")
}
#if os(iOS) || os(OSX) || os(watchOS) || os(tvOS)
func testDecimalParsing() throws {
let data = try readFixture("sample", withExtension: "json")
// Decode the data and make sure it contains no .double values
let json = try JSON.decode(data, options: [.useDecimals])
let value = json.walk { value in
return value.isDouble ? value : .none
}
XCTAssertNil(value)
}
#endif
func testReencode() throws {
// sample.json contains a lot of edge cases, so we'll make sure we can re-encode it and re-decode it and get the same thing
let data = try readFixture("sample", withExtension: "json")
do {
let json = try JSON.decode(data)
let encoded = JSON.encodeAsString(json)
let json2 = try JSON.decode(encoded)
if !json.approximatelyEqual(json2) { // encoding/decoding again doesn't necessarily match the exact numeric precision of the original
// NB: Don't use XCTAssertEquals because this JSON is too large to be printed to the console
XCTFail("Re-encoded JSON doesn't match original")
}
}
#if os(iOS) || os(OSX) || os(watchOS) || os(tvOS)
do {
// test again with decimals
let json = try JSON.decode(data, options: [.useDecimals])
let encoded = JSON.encodeAsString(json)
let json2 = try JSON.decode(encoded, options: [.useDecimals])
if json != json2 { // This preserves all precision, but may still convert between int64 and decimal so we can't use matchesJSON
// NB: Don't use XCTAssertEquals because this JSON is too large to be printed to the console
try json.debugMatches(json2, ==)
XCTFail("Re-encoded JSON doesn't match original")
}
}
#endif
}
func testConversions() {
XCTAssertEqual(JSON(true), JSON.bool(true))
XCTAssertEqual(JSON(42 as Int64), JSON.int64(42))
XCTAssertEqual(JSON(42 as Double), JSON.double(42))
XCTAssertEqual(JSON(42 as Int), JSON.int64(42))
#if os(iOS) || os(OSX) || os(watchOS) || os(tvOS)
XCTAssertEqual(JSON(42 as Decimal), JSON.decimal(42))
#endif
XCTAssertEqual(JSON("foo"), JSON.string("foo"))
XCTAssertEqual(JSON(["foo": true]), ["foo": true])
XCTAssertEqual(JSON([JSON.bool(true)] as JSONArray), [true]) // JSONArray
XCTAssertEqual(JSON([true].lazy.map(JSON.bool)), [true]) // Sequence of JSON
XCTAssertEqual(JSON([["foo": true], ["bar": 42]].lazy.map(JSONObject.init)), [["foo": true], ["bar": 42]]) // Sequence of JSONObject
XCTAssertEqual(JSON([[1,2,3],[4,5,6]].lazy.map(JSONArray.init)), [[1,2,3],[4,5,6]]) // Sequence of JSONArray
}
#if os(iOS) || os(OSX) || os(watchOS) || os(tvOS)
func testJSONErrorNSErrorDescription() throws {
let jserror: JSONError?
do {
let json: JSON = ["foo": 1]
_ = try json.getString("foo")
jserror = nil
} catch let error as JSONError {
jserror = error
}
guard let error = jserror else {
XCTFail("Expected error, found nothing")
return
}
XCTAssertEqual(String(describing: error), error.localizedDescription)
}
#endif
func testDepthLimit() {
func assertThrowsDepthError(_ string: String, limit: Int, file: StaticString = #file, line: UInt = #line) {
XCTAssertThrowsError(try JSON.decode(string, options: [.depthLimit(limit)]), file: file, line: line) { (error) in
switch error {
case JSONDecoderError.exceededDepthLimit: break
default: XCTFail("Expected JSONDecoderError.exceededDepthLimit, got \(error)", file: file, line: line)
}
}
}
assertThrowsDepthError("[[[[[1]]]]]", limit: 3)
assertMatchesJSON(try JSON.decode("[[[[[1]]]]]", options: [.depthLimit(10)]), [[[[[1]]]]])
assertThrowsDepthError("{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":1}}}}}", limit: 3)
assertMatchesJSON(try JSON.decode("{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":1}}}}}", options: [.depthLimit(10)]), ["a":["a":["a":["a":["a":1]]]]])
// Depth limit of 0 means just values, no arrays/dictionaries at all
assertMatchesJSON(try JSON.decode("null", options: [.depthLimit(0)]), nil)
assertMatchesJSON(try JSON.decode("3", options: [.depthLimit(0)]), 3)
assertThrowsDepthError("[]", limit: 0)
assertThrowsDepthError("{}", limit: 0)
// Depth limit of 1 means one level of array/dictionary
assertMatchesJSON(try JSON.decode("[1]", options: [.depthLimit(1)]), [1])
assertMatchesJSON(try JSON.decode("{\"a\":1}", options: [.depthLimit(1)]), ["a":1])
assertThrowsDepthError("[[1]]", limit: 1)
assertThrowsDepthError("{\"a\":{}}", limit: 1)
assertThrowsDepthError("[{}]", limit: 1)
assertThrowsDepthError("{\"a\":[]}", limit: 1)
}
func testBOMDetection() {
// UTF-32BE with BOM
assertMatchesJSON(try JSON.decode("\u{FEFF}42".data(using: .utf32BigEndian)!), 42)
// UTF-32LE with BOM
assertMatchesJSON(try JSON.decode("\u{FEFF}42".data(using: .utf32LittleEndian)!), 42)
// UTF-16BE with BOM
assertMatchesJSON(try JSON.decode("\u{FEFF}42".data(using: .utf16BigEndian)!), 42)
// UTF-16LE with BOM
assertMatchesJSON(try JSON.decode("\u{FEFF}42".data(using: .utf16LittleEndian)!), 42)
// UTF8 with BOM
assertMatchesJSON(try JSON.decode("\u{FEFF}42".data(using: .utf8)!), 42)
}
func testUnicodeHeuristicDetection() {
// UTF-32BE
assertMatchesJSON(try JSON.decode("42".data(using: .utf32BigEndian)!), 42)
// UTF-32LE
assertMatchesJSON(try JSON.decode("42".data(using: .utf32LittleEndian)!), 42)
// UTF-16BE
assertMatchesJSON(try JSON.decode("42".data(using: .utf16BigEndian)!), 42)
// UTF-16LE
assertMatchesJSON(try JSON.decode("42".data(using: .utf16LittleEndian)!), 42)
// UTF8
assertMatchesJSON(try JSON.decode("42".data(using: .utf8)!), 42)
}
}
/// Tests both `JSONDecoder`'s streaming mode and `JSONStreamDecoder`.
class JSONStreamDecoderTests: XCTestCase {
func testDecoderStreamingMode() {
func decodeStream(_ input: String) throws -> [JSON] {
let parser = JSONParser(input.unicodeScalars, options: [.streaming])
var decoder = JSONDecoder(parser)
return try decoder.decodeStream()
}
func assertMatchesEvents(_ input: String, _ expected: [JSON], file: StaticString = #file, line: UInt = #line) {
do {
let events = try decodeStream(input)
for (i, (event, value)) in zip(events, expected).enumerated() {
if !matchesJSON(event, value) {
XCTFail("event \(i+1) (\(event)) does not equal \(value)", file: file, line: line)
}
if events.count > expected.count {
XCTFail("unexpected event \(expected.count+1)", file: file, line: line)
}
if events.count < expected.count {
XCTFail("expected event \(events.count+1) (\(expected[events.count])), found nil", file: file, line: line)
}
}
} catch {
XCTFail("assertMatchesEvents - error thrown: \(error)", file: file, line: line)
}
}
assertMatchesEvents("", [])
assertMatchesEvents(" ", [])
assertMatchesEvents("true", [true])
assertMatchesEvents("true false", [true, false])
assertMatchesEvents("{\"a\": 1}{\"a\": 2}3", [["a": 1], ["a": 2], 3])
XCTAssertThrowsError(try decodeStream("true q")) { (error) in
switch error {
case let error as JSONParserError:
XCTAssertEqual(error, JSONParserError(code: .invalidSyntax, line: 0, column: 6))
default:
XCTFail("expected JSONParserError, found \(error)")
}
}
}
func testStreamingDecoder() {
func assertMatchesValues(_ input: String, _ expected: [JSONStreamValue], file: StaticString = #file, line: UInt = #line) {
for (i, (value, expected)) in zip(JSON.decodeStream(input), expected).enumerated() {
switch (value, expected) {
case let (.json(value), .json(expected)):
if !matchesJSON(value, expected) {
XCTFail("value \(i+1) - (\(value)) does not equal \(expected)", file: file, line: line)
}
case let (.error(error), .error(expected)):
if error != expected {
XCTFail("error \(i+1) - (\(error)) does not equal \(expected)", file: file, line: line)
}
case let (.json(value), .error(expected)):
XCTFail("value \(i+1) - expected error \(expected), found value \(value)", file: file, line: line)
case let (.error(error), .json(expected)):
XCTFail("value \(i+1) - expected value \(expected), found error \(error)", file: file, line: line)
}
}
// Also check the behavior of values()
do {
let expectedValues = try expected.map({ try $0.unwrap() })
do {
let values = try JSON.decodeStream(input).values()
XCTAssertEqual(values, expectedValues, file: file, line: line)
} catch {
XCTFail("unexpected error found decoding JSON stream - \(error)", file: file, line: line)
}
} catch let expectedError as JSONParserError {
XCTAssertThrowsError(try JSON.decodeStream(input).values()) { (error) in
switch error {
case let error as JSONParserError:
XCTAssertEqual(error, expectedError, file: file, line: line)
default:
XCTFail("expected \(expectedError), found \(error)", file: file, line: line)
}
}
} catch {
XCTFail(file: file, line: line) // unreachable
}
}
func assertMatchesEvents(_ input: String, _ expected: [JSON], file: StaticString = #file, line: UInt = #line) {
assertMatchesValues(input, expected.map(JSONStreamValue.json), file: file, line: line)
}
assertMatchesEvents("", [])
assertMatchesEvents(" ", [])
assertMatchesEvents("true", [true])
assertMatchesEvents("true false", [true, false])
assertMatchesEvents("{\"a\": 1}{\"a\": 2}3", [["a": 1], ["a": 2], 3])
assertMatchesValues("true q", [.json(true), .error(JSONParserError(code: .invalidSyntax, line: 0, column: 6))])
// After a parser error, nothing more is parsed
assertMatchesValues("true q true", [.json(true), .error(JSONParserError(code: .invalidSyntax, line: 0, column: 6))])
}
}
class JSONBenchmarks: XCTestCase {
func testCompareCocoa() {
do {
let json = try JSON.decode(bigJson)
let jsonObj = json.ns as! NSObject
let cocoa = try JSONSerialization.jsonObject(with: bigJson) as! NSObject
XCTAssertEqual(jsonObj, cocoa)
let cocoa2 = try JSONSerialization.jsonObject(with: JSON.encodeAsData(json)) as! NSObject
XCTAssertEqual(jsonObj, cocoa2)
} catch {
XCTFail(String(describing: error))
}
}
func testDecodePerformance() {
measure { [bigJson] in
for _ in 0..<10 {
do {
_ = try JSON.decode(bigJson)
} catch {
XCTFail("error parsing json: \(error)")
}
}
}
}
func testDecodeDecimalPerformance() {
measure { [bigJson] in
for _ in 0..<10 {
do {
_ = try JSON.decode(bigJson, options: [.useDecimals])
} catch {
XCTFail("error parsing json: \(error)")
}
}
}
}
func testDecodePerformanceCocoa() {
measure { [bigJson] in
for _ in 0..<10 {
do {
_ = try JSONSerialization.jsonObject(with: bigJson, options: [])
} catch {
XCTFail("error parsing json: \(error)")
}
}
}
}
func testEncodePerformance() {
do {
let json = try JSON.decode(bigJson)
measure {
for _ in 0..<10 {
_ = JSON.encodeAsData(json)
}
}
} catch {
XCTFail("error parsing json: \(error)")
}
}
func testEncodeCocoaPerformance() {
do {
let json = try JSON.decode(bigJson).ns
measure {
for _ in 0..<10 {
do {
_ = try JSONSerialization.data(withJSONObject: json)
} catch {
XCTFail("error encoding json: \(error)")
}
}
}
} catch {
XCTFail("error parsing json: \(error)")
}
}
func testEncodePrettyPerformance() {
do {
let json = try JSON.decode(bigJson)
measure {
for _ in 0..<10 {
_ = JSON.encodeAsData(json, options: [.pretty])
}
}
} catch {
XCTFail("error parsing json: \(error)")
}
}
func testEncodePrettyCocoaPerformance() {
do {
let json = try JSON.decode(bigJson).ns
measure {
for _ in 0..<10 {
do {
_ = try JSONSerialization.data(withJSONObject: json, options: [.prettyPrinted])
} catch {
XCTFail("error encoding json: \(error)")
}
}
}
} catch {
XCTFail("error parsing json: \(error)")
}
}
func testDecodeSampleJSONPerformance() throws {
let data = try readFixture("sample", withExtension: "json")
measure {
for _ in 0..<10 {
do {
_ = try JSON.decode(data)
} catch {
return XCTFail("error parsing json: \(error)")
}
}
}
}
func testDecodeSampleJSONDecimalPerformance() throws {
let data = try readFixture("sample", withExtension: "json")
measure {
for _ in 0..<10 {
do {
_ = try JSON.decode(data, options: [.useDecimals])
} catch {
return XCTFail("error parsing json: \(error)")
}
}
}
}
func testDecodeSampleJSONCocoaPerformance() throws {
let data = try readFixture("sample", withExtension: "json")
measure {
for _ in 0..<10 {
do {
_ = try JSONSerialization.jsonObject(with: data)
} catch {
return XCTFail("error parsing json: \(error)")
}
}
}
}
}
func assertMatchesJSON(_ a: @autoclosure () throws -> JSON, _ b: @autoclosure () -> JSON, file: StaticString = #file, line: UInt = #line) {
do {
let a = try a(), b = b()
if !matchesJSON(a, b) {
XCTFail("expected \(b), found \(a)", file: file, line: line)
}
} catch {
XCTFail(String(describing: error), file: file, line: line)
}
}
/// Similar to JSON's equality test but does not convert between numeric values.
private func matchesJSON(_ a: JSON, _ b: JSON) -> Bool {
switch (a, b) {
case (.array(let a), .array(let b)):
return a.count == b.count && !zip(a, b).contains(where: {!matchesJSON($0, $1)})
case (.object(let a), .object(let b)):
guard a.count == b.count else { return false }
for (key, value) in a {
guard let bValue = b[key], matchesJSON(value, bValue) else {
return false
}
}
return true
case (.string(let a), .string(let b)):
return a == b
case (.int64(let a), .int64(let b)):
return a == b
case (.double(let a), .double(let b)):
return a == b
case (.decimal(let a), .decimal(let b)):
return a == b
case (.null, .null):
return true
case (.bool(let a), .bool(let b)):
return a == b
default:
return false
}
}
extension JSON {
/// Performs an equality test, but accepts nearly-equal `Double` values.
func approximatelyEqual(_ other: JSON) -> Bool {
switch (self, other) {
case (.double(let a), .double(let b)):
// we're going to cheat and just convert them to Floats and compare that way.
// We just care about equal up to a given precision, and so dropping down to Float precision should give us that.
return Float(a) == Float(b)
case (.array(let a), .array(let b)):
return a.count == b.count && !zip(a, b).lazy.contains(where: { !$0.approximatelyEqual($1) })
case (.object(let a), .object(let b)):
return a.count == b.count && !a.contains(where: { (k,v) in b[k].map(
{ !$0.approximatelyEqual(v) }) ?? true })
default:
return self == other
}
}
/// Invokes the given block on every JSON value within `self`.
/// For objects and arrays, the block is run with the object/array first, and then
/// with its contents afterward.
func walk<T>(using f: (JSON) throws -> T?) rethrows -> T? {
if let result = try f(self) {
return result
}
switch self {
case .object(let obj):
for value in obj.values {
if let result = try value.walk(using: f) {
return result
}
}
case .array(let ary):
for elt in ary {
if let result = try elt.walk(using: f) {
return result
}
}
default:
break
}
return nil
}
/// Walks two JSON values in sync, performing the given equality test on
/// all leaf values and throwing an error when a mismatch is found.
/// The equality test is not performed on objects or arrays.
func debugMatches(_ other: JSON, _ compare: (JSON, JSON) -> Bool) throws {
enum Error: LocalizedError {
case objectCountMismatch
case objectKeyMismatch
case arrayCountMismatch
case typeMismatch
case equalityFailure(JSON, JSON)
var errorDescription: String? {
switch self {
case .objectCountMismatch: return "object count mismatch"
case .objectKeyMismatch: return "object key mismatch"
case .arrayCountMismatch: return "array count mismatch"
case .typeMismatch: return "value type mismatch"
case let .equalityFailure(a, b): return "\(String(reflecting: a)) is not equal to \(String(reflecting: b))"
}
}
}
switch (self, other) {
case (.object(let a), .object(let b)):
guard a.count == b.count else { throw Error.objectCountMismatch }
for (k, v) in a {
guard let v2 = b[k] else { throw Error.objectKeyMismatch }
try v.debugMatches(v2, compare)
}
case (.object, _), (_, .object):
throw Error.typeMismatch
case (.array(let a), .array(let b)):
guard a.count == b.count else { throw Error.arrayCountMismatch }
for (v, v2) in zip(a,b) {
try v.debugMatches(v2, compare)
}
case (.array, _), (_, .array):
throw Error.typeMismatch
default:
if !compare(self, other) {
throw Error.equalityFailure(self, other)
}
}
}
}
| apache-2.0 | 0a1bc01955106ab26fbf4bc46443bdd7 | 39.705882 | 148 | 0.529412 | 4.294214 | false | true | false | false |
norary3/DewDateCalendar | CalendarDemo/AddTableViewController.swift | 1 | 13158 | //
// AddTableViewController.swift
// DewDate
//
// Created by cscoi027 on 2016. 8. 24..
// Copyright © 2016년 Koreauniv. All rights reserved.
//
import UIKit
import EventKit
extension String {
public func indexOfCharacter(_ char: Character) -> Int? {
if let idx = self.characters.index(of: char) {
return self.characters.distance(from: self.startIndex, to: idx)
}
return nil
}
func toDateTime(_ dateFormatter:DateFormatter) -> Date
{
//Parse into NSDate
let dateFromString : Date = dateFormatter.date(from: self)!
//Return Parsed Date
return dateFromString
}
}
extension Date
{
func year() -> Int
{
let calendar = Calendar.current
let components = (calendar as NSCalendar).components(.year, from: self)
let year = components.year
return year!
}
func month() -> Int
{
let calendar = Calendar.current
let components = (calendar as NSCalendar).components(.month, from: self)
let month = components.month
return month!
}
func day() -> Int
{
let calendar = Calendar.current
let components = (calendar as NSCalendar).components(.day, from: self)
let day = components.day
return day!
}
func hour() -> Int
{
//Get Hour
let calendar = Calendar.current
let components = (calendar as NSCalendar).components(.hour, from: self)
let hour = components.hour
//Return Hour
return hour!
}
func minute() -> Int
{
//Get Minute
let calendar = Calendar.current
let components = (calendar as NSCalendar).components(.minute, from: self)
let minute = components.minute
//Return Minute
return minute!
}
func toTimeString(_ formatter:DateFormatter) -> String
{
//Get Time String
let timeString = formatter.string(from: self)
//Return Time String
return timeString
}
}
class AddTableViewController: UITableViewController {
var convertingString: String?
let solCal = Calendar.init(identifier: .gregorian)
let lunarCal = Calendar.init(identifier: .chinese)
var eventTitle:String = ""
var eventLocation = ""
var eventIsAllDay = false
var isLunar = false
var eventStart:Date = Date()
var eventEnd:Date = Date().addingTimeInterval(60 * 60)
//var eventRepeat:EKRecurrenceRule? = nil
//var eventAlarm:EKAlarm? = nil
var eventURL:URL = NSURLComponents().url!
var eventMemo = ""
//Create Date Formatter
var dateFormatter = DateFormatter()
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var startLabel: UILabel!
@IBOutlet weak var endLabel: UILabel!
//@IBOutlet weak var repeatLabel: UILabel!
//@IBOutlet weak var alarmLabel: UILabel!
@IBOutlet weak var urlTextField: UITextField!
@IBOutlet weak var memoTextField: UITextView!
@IBAction func isAllDaySwitch(_ sender: AnyObject) {
let allDaySwitch = sender as! UISwitch
let allDayBool:Bool = allDaySwitch.isOn
self.eventIsAllDay = allDayBool
if eventIsAllDay {
//Specify Format of String to Parsez
self.dateFormatter.dateFormat = "yyyy-MM-dd"
self.startDatePickerValue.datePickerMode = UIDatePickerMode.date
self.endDatePickerValue.datePickerMode = UIDatePickerMode.date
self.startLabel.text = self.eventStart.toTimeString(self.dateFormatter)
self.endLabel.text = self.eventEnd.toTimeString(self.dateFormatter)
} else {
//Specify Format of String to Parsez
self.dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
self.startDatePickerValue.datePickerMode = UIDatePickerMode.dateAndTime
self.endDatePickerValue.datePickerMode = UIDatePickerMode.dateAndTime
self.startLabel.text = self.eventStart.toTimeString(self.dateFormatter)
self.endLabel.text = self.eventEnd.toTimeString(self.dateFormatter)
}
}
@IBAction func isLunarSwitch(_ sender: Any) {
let lunarwitch = sender as! UISwitch
self.isLunar = lunarwitch.isOn
if self.isLunar {
//Specify Format of String to Parsez
self.dateFormatter.calendar = lunarCal
self.startDatePickerValue.calendar = lunarCal
self.endDatePickerValue.calendar = lunarCal
} else {
//Specify Format of String to Parsez
self.dateFormatter.calendar = solCal
self.startDatePickerValue.calendar = solCal
self.endDatePickerValue.calendar = solCal
}
self.startLabel.text = self.eventStart.toTimeString(self.dateFormatter)
self.endLabel.text = self.eventEnd.toTimeString(self.dateFormatter)
}
@IBOutlet weak var startDatePickerValue: UIDatePicker!
@IBAction func startDatePicker(_ sender: AnyObject) {
//self.endCheck()
self.eventStart = startDatePickerValue.date
self.startLabel.text = eventStart.toTimeString(self.dateFormatter)
}
@IBOutlet weak var endDatePickerValue: UIDatePicker!
@IBAction func endDatePicker(_ sender: AnyObject) {
//self.endCheck()
self.eventEnd = endDatePickerValue.date
self.endLabel.text = eventEnd.toTimeString(self.dateFormatter)
}
@IBAction func cancel(_ sender: AnyObject) {
self.dismiss(animated: true) {
}
}
@IBAction func add(_ sender: AnyObject) {
self.dismiss(animated: true) {
let eventStore = EKEventStore()
if let newEventTitle = self.titleTextField.text { self.eventTitle = newEventTitle }
if let newEventLocation = self.locationTextField.text { self.eventLocation = newEventLocation }
self.eventStart = self.startDatePickerValue.date
self.eventEnd = self.endDatePickerValue.date
if let newEventURL = URL(string: self.urlTextField.text!) { self.eventURL = newEventURL }
if let newEventMemo = self.memoTextField.text { self.eventMemo = newEventMemo }
if (EKEventStore.authorizationStatus(for: .event) != EKAuthorizationStatus.authorized) {
eventStore.requestAccess(to: .event, completion: {
granted, error in
if granted {
self.createEvent(eventStore)
} else {
self.failAlert()
}
})
} else {
self.createEvent(eventStore)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
//print("Add View : HI")
//Specify Format of String to Parse
self.dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
DispatchQueue.main.async{
self.titleTextField.text = self.eventTitle
self.locationTextField.text = self.eventLocation
self.startLabel.text = self.eventStart.toTimeString(self.dateFormatter)
self.endLabel.text = self.eventEnd.toTimeString(self.dateFormatter)
self.memoTextField.text = self.eventMemo
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
switch section {
case 0:
return 2
case 1:
return 6
case 2:
return 2
default:
return 0
}
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
var StartPickerRowHeight:CGFloat = 0.0
var EndPickerRowHeight:CGFloat = 0.0
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath {
case IndexPath(row: 2, section: 1):
startDatePickerValue.setDate(self.eventStart, animated: false)
if StartPickerRowHeight < 100 { StartPickerRowHeight = 210.0 }
else { StartPickerRowHeight = 0.0 }
self.tableView.reloadData()
case IndexPath(row: 4, section: 1):
endDatePickerValue.setDate(self.eventEnd, animated: false)
if EndPickerRowHeight < 100 { EndPickerRowHeight = 210.0 }
else { EndPickerRowHeight = 0.0 }
self.tableView.reloadData()
default:
if indexPath != IndexPath(row: 2, section: 1) && indexPath != IndexPath(row: 4, section: 1) {
StartPickerRowHeight = 0.0
EndPickerRowHeight = 0.0
self.tableView.reloadData()
}
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
switch indexPath {
case IndexPath(row: 3, section: 1):
return StartPickerRowHeight
case IndexPath(row: 5, section: 1):
return EndPickerRowHeight
case IndexPath(row: 1, section: 2):
return 150.0
default:
return 44.0
}
}
// Creates an event in the EKEventStore. The method assumes the eventStore is created and
// accessible
func createEvent(_ eventStore: EKEventStore) {
let event = EKEvent(eventStore: eventStore)
event.title = self.eventTitle
event.isAllDay = self.eventIsAllDay
event.startDate = self.eventStart
event.endDate = self.eventEnd
event.location = self.eventLocation
event.notes = self.eventMemo
event.url = self.eventURL
/*
if let alarm = self.eventAlarm {
event.alarms = [alarm]
}
*/
event.calendar = eventStore.defaultCalendarForNewEvents
do {
try eventStore.save(event, span: .thisEvent)
} catch {
print("Bad things happened creating evnet")
}
}
func failAlert() {
let addAlert = UIAlertController(title: "\(self.eventTitle) 일정을 저장할 수 없습니다. DewDate가 캘린더에 접근할 수 있도록 허가해 주세요", message: nil, preferredStyle: .actionSheet)
let exitAction = UIAlertAction(title: "종료", style: .cancel, handler: { (action:UIAlertAction) -> Void in
print ("종료 선택")
})
addAlert.addAction(exitAction)
self.present(addAlert, animated: true, completion: nil)
}
}
| mit | d794e563aaa4f630421a711ed18947b1 | 33.616402 | 161 | 0.620864 | 4.877003 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/Sensors/Pitch/Harmonic.swift | 1 | 2979 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* 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
/// Represents a harmonic relationship between two frequencies.
final class Harmonic {
internal var peakA: Peak
internal var peakB: Peak
internal var termA: Int
internal var termB: Int
/// Create harmonic ratio relationship between two frequencies, peak a, and peak b, along with
/// the antecedent term of the ratio (termA) and consequent term (termB).
init(peakA: Peak, peakB: Peak, termA: Int, termB: Int) {
self.peakA = peakA
self.peakB = peakB
self.termA = termA
self.termB = termB
}
/// Find term associated with the given peak. Assumes that the peak is part of this relationship
/// otherwise returns 0.
func getTermForPeak(_ peak: Peak) -> Int {
if peak == peakA {
return termA
} else if peak == peakB {
return termB
}
return 0
}
/// Adjusts the harmonic based on other harmonic relationships.
func adjustHarmonic() {
var multiplier = 0
let peakADescendingHarmonicTerms = peakA.harmonicTerms.sorted { $0 > $1 }
for term in peakADescendingHarmonicTerms {
if term <= termA {
// We only care about terms larger than a.
break
}
if term % termA == 0 {
multiplier = term / termA
break
}
}
let peakBDescendingHarmonicTerms = peakB.harmonicTerms.sorted { $0 > $1 }
for term in peakBDescendingHarmonicTerms {
if term <= termB {
// We only care about terms larger than b.
break
}
if term % termB == 0 {
let m = term / termB
if m > multiplier {
multiplier = m
}
break
}
}
if multiplier != 0 {
multiply(multiplier)
}
}
private func multiply(_ multiplier: Int) {
termA *= multiplier
termB *= multiplier
}
static func addHarmonic(peakA: Peak, peakB: Peak, termA: Int, termB: Int) -> Harmonic {
let harmonic = Harmonic(peakA: peakA, peakB: peakB, termA: termA, termB: termB)
peakA.addHarmonic(harmonic)
peakB.addHarmonic(harmonic)
return harmonic
}
}
extension Harmonic: Equatable {
static func == (lhs: Harmonic, rhs: Harmonic) -> Bool {
return lhs.peakA == rhs.peakA && lhs.peakB == rhs.peakB
}
}
extension Harmonic: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(peakA)
hasher.combine(peakB)
}
}
| apache-2.0 | 4b2669e60b1aed14d610f91b14a811ac | 25.362832 | 98 | 0.651225 | 3.780457 | false | false | false | false |
dkhamsing/osia | Swift/osia/List/ListController.swift | 1 | 2543 | //
// ListController.swift
// osia
//
// Created by Daniel Khamsing on 9/6/17.
// Copyright © 2017 Daniel Khamsing. All rights reserved.
//
import UIKit
final class ListController: UIViewController {
// Data
var category = Category()
var delegate: Selectable?
// UI
private var tableView = UITableView(frame: .zero, style: .insetGrouped)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.setup()
}
}
private struct Constant {
static let rowHeight: CGFloat = 55
}
extension ListController {
func reload() {
tableView.reloadData()
}
}
private extension ListController {
func setup() {
let f = view.frame
tableView.frame = f
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(tableView)
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = Constant.rowHeight
tableView.register(AppCell.self, forCellReuseIdentifier: AppCell.ReuseIdentifier)
tableView.register(CategoryCell.self, forCellReuseIdentifier: CategoryCell.ReuseIdentifier)
}
}
extension ListController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return category.list.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = category.list[indexPath.row]
if let cat = item as? Category {
let c = tableView.dequeueReusableCell(withIdentifier: CategoryCell.ReuseIdentifier, for: indexPath) as! CategoryCell
c.category = cat
return c
}
guard let app = item as? App else { return UITableViewCell() }
let c = tableView.dequeueReusableCell(withIdentifier: AppCell.ReuseIdentifier, for: indexPath) as! AppCell
c.app = app
return c
}
}
extension ListController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let item = category.list[indexPath.row]
if let app = item as? App {
delegate?.didSelect(app)
}
else if let cat = item as? Category {
delegate?.didSelect(cat)
}
}
}
| mit | 76a48939858890b56038342f0b530ce4 | 27.886364 | 128 | 0.660504 | 4.916828 | false | false | false | false |
swiftde/Udemy-Swift-Kurs | SortiererTest/SortiererTest/AppDelegate.swift | 1 | 6129 | //
// AppDelegate.swift
// SortiererTest
//
// Created by Udemy on 26.02.15.
// Copyright (c) 2015 benchr. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "de.benchr.SortiererTest" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("SortiererTest", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SortiererTest.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| apache-2.0 | 3a1294ee4efec09050e93f6e50e2c61d | 54.216216 | 290 | 0.716756 | 5.728037 | false | false | false | false |
cactis/SwiftEasyKit | Source/Classes/SingleChoice.swift | 1 | 4607 | //
// SingleChoice.swift
//
// Created by ctslin on 4/8/16.
import UIKit
open class MultipleChoiceTable: ChoiceTable {
public var value: [Int] = [] {
didSet { refreshData() }
}
public var didChange: (_ value: [Int]) -> () = { _ in}
public init(items: [String], value: [Int]) {
super.init(frame: .zero)
self.items = items
self.value = value
refreshData()
}
required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
public func refreshData() {
collectionData = []
(0...items.count - 1).forEach { (index) in
collectionData.append((title: items[index], checked: value.index(of: index) != nil))
}
tableView.reloadData()
}
override open func didSelect(_ indexPath: NSIndexPath?) {
if let index = value.index(of: indexPath!.row) {
value.remove(at: index)
} else {
value.append(indexPath!.row)
}
didChange(value)
}
}
open class SingleChoiceTable: ChoiceTable {
public var value: Int = -1 {
didSet {
refreshData()
}
}
public var didChange: (_ value: Int) -> () = { _ in}
public init(items: [String]) {
super.init(frame: .zero)
self.items = items
refreshData()
}
public init(items: [String], value: Int) {
super.init(frame: .zero)
self.items = items
self.value = value
refreshData()
}
public func refreshData() {
collectionData = []
(0...items.count - 1).forEach { (index) in
collectionData.append((title: items[index], checked: index == value))
}
tableView.reloadData()
}
override open func didSelect(_ indexPath: NSIndexPath?) {
value = indexPath!.row
didChange(value)
}
required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
open class ChoiceTable: DefaultView, UITableViewDelegate, UITableViewDataSource {
public var tableView: UITableView!
public var CellIdentifier = "CELL"
public var items: [String] = []
public var collectionData: [(title: String, checked: Bool)] = []
override open func layoutUI() {
super.layoutUI()
tableView = tableView(ChoiceCell.self, identifier: CellIdentifier)
layout([tableView])
}
override open func styleUI() {
super.styleUI()
tableView.separatorStyle = .singleLine
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier) as! ChoiceCell
cell.data = collectionData[indexPath.row]
cell.whenTapped(self, action: #selector(cellTapped))
return cell
}
@objc public func cellTapped(_ sender: UIGestureRecognizer) {
// didSelect(sender.indexPathInTableView(tableView))
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return collectionData.count
}
@nonobjc public func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return cellHeight()
}
public func didSelect(_ indexPath: NSIndexPath?) { }
public func cellHeight() -> CGFloat {
return K.Size.Text.normal * 3
}
override open func layoutSubviews() {
super.layoutSubviews()
tableView.fillSuperview()
}
open class ChoiceCell: TableViewCell {
public var label = UILabel()
public var icon = UIImageView()
public var checked: Bool = false { didSet { refreshIcon() } }
public var iconSize = 24.em
public var data: (title: String, checked: Bool) = (title: "", checked: false) {
didSet {
label.texted(data.title)
checked = data.checked
}
}
override open func layoutUI() {
super.layoutUI()
layout([label, icon])
}
override open func styleUI() {
super.styleUI()
label.styled()
backgroundColored(UIColor.white)
}
public func refreshIcon() {
if checked {
icon.image = getIcon(.check, options: ["color": K.Color.buttonBg])
} else {
icon.image = UIImage()
}
}
override open func layoutSubviews() {
super.layoutSubviews()
label.anchorAndFillEdge(.left, xPad: 20, yPad: 0, otherSize: label.textWidth())
icon.anchorToEdge(.right, padding: 10, width: iconSize, height: iconSize)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
| mit | b254ad8f35b879fe2b12085e73b2ff31 | 24.882022 | 119 | 0.654656 | 4.218864 | false | false | false | false |
chrisjmendez/swift-exercises | Concurrency/MyAsync/Carthage/Checkouts/Async/AsyncTest/AsyncGroupTests.swift | 1 | 2674 | //
// AsyncGroupTests.swift
// Async
//
// Created by Eneko Alonso on 2/2/16.
// Copyright © 2016 developmunk. All rights reserved.
//
import Foundation
import XCTest
class AsyncGroupTests: XCTestCase {
// Typical testing time delay. Must be bigger than `timeMargin`
let timeDelay = 0.3
// Allowed error for timeDelay
let timeMargin = 0.2
func testBackgroundGroup() {
let expectation = expectationWithDescription("Expected on background queue")
let group = AsyncGroup()
group.background {
XCTAssertEqual(qos_class_self(), QOS_CLASS_BACKGROUND, "On \(qos_class_self().description) (expected \(QOS_CLASS_BACKGROUND.description))")
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeMargin, handler: nil)
}
func testGroupWait() {
var complete = false
let group = AsyncGroup()
group.background {
XCTAssertEqual(qos_class_self(), QOS_CLASS_BACKGROUND, "On \(qos_class_self().description) (expected \(QOS_CLASS_BACKGROUND.description))")
complete = true
}
group.wait(seconds: timeMargin)
XCTAssertEqual(complete, true)
}
func testMultipleGroups() {
var count = 0
let group = AsyncGroup()
for _ in 1...10 {
group.background {
XCTAssertEqual(qos_class_self(), QOS_CLASS_BACKGROUND, "On \(qos_class_self().description) (expected \(QOS_CLASS_BACKGROUND.description))")
count++
}
}
group.wait(seconds: timeMargin)
XCTAssertEqual(count, 10)
}
func testCustomBlockGroups() {
var count = 0
let group = AsyncGroup()
for _ in 1...10 {
group.enter()
Async.background {
XCTAssertEqual(qos_class_self(), QOS_CLASS_BACKGROUND, "On \(qos_class_self().description) (expected \(QOS_CLASS_BACKGROUND.description))")
count++
group.leave()
}
}
group.wait(seconds: timeMargin)
XCTAssertEqual(count, 10)
}
func testNestedAsyncGroups() {
var count = 0
let group = AsyncGroup()
for _ in 1...10 {
group.background {
XCTAssertEqual(qos_class_self(), QOS_CLASS_BACKGROUND, "On \(qos_class_self().description) (expected \(QOS_CLASS_BACKGROUND.description))")
group.enter()
Async.background {
count++
group.leave()
}
}
}
group.wait(seconds: timeMargin)
XCTAssertEqual(count, 10)
}
}
| mit | 8d053bb6a709cbc8919642ad8c8f4013 | 30.447059 | 155 | 0.573887 | 4.569231 | false | true | false | false |
ricardorauber/iOS-Swift | iOS-Swift.playground/Pages/Predicates.xcplaygroundpage/Contents.swift | 1 | 4852 | //: ## Predicates
//: ----
//: [Previous](@previous)
import Foundation
class Country: NSObject {
var name: String
init(name: String) {
self.name = name
}
}
class Manufacturer: NSObject {
var name: String
var country: Country
init(name: String, country: Country) {
self.name = name
self.country = country
}
}
class Car: NSObject {
var name: String
var manufacturer: Manufacturer
var price: Float
init(name: String, manufacturer: Manufacturer, price: Float) {
self.name = name
self.manufacturer = manufacturer
self.price = price
}
}
let usa = Country(name: "United States of America")
let germany = Country(name: "Germany")
let ford = Manufacturer(name: "Ford", country: usa)
let volkswagen = Manufacturer(name: "Volkswagen", country: germany)
let porsche = Manufacturer(name: "Porsche", country: germany)
let fiesta = Car(name: "Fiesta", manufacturer: ford, price: 15000)
let mustang = Car(name: "Mustang", manufacturer: ford, price: 25000)
let golf = Car(name: "Golf", manufacturer: volkswagen, price: 25000)
let touareg = Car(name: "Touareg", manufacturer: volkswagen, price: 45000)
let boxster = Car(name: "Boxster", manufacturer: porsche, price: 55000)
let panamera = Car(name: "Panamera", manufacturer: porsche, price: 75000)
let cars: NSArray = [fiesta, mustang, golf, touareg, boxster, panamera]
//: Equal
let usaPredicate = NSPredicate(format: "manufacturer.country = %@", usa)
let carsFromUsa = cars.filteredArrayUsingPredicate(usaPredicate)
let germanyPredicate = NSPredicate(format: "manufacturer.country.name = %@", germany.name)
let carsFromGermany = cars.filteredArrayUsingPredicate(germanyPredicate)
//: Not
let anyCarsNotFromGermanyPredicate = NSPredicate(format: "NOT manufacturer.country.name = %@", germany.name)
let anyCarsNotFromGermany = cars.filteredArrayUsingPredicate(anyCarsNotFromGermanyPredicate)
//: Less
let cheapCarsPredicate = NSPredicate(format: "price < 20000")
let cheapCars = cars.filteredArrayUsingPredicate(cheapCarsPredicate)
//: Variables Substitution
let expensiveCarsPredicate = NSPredicate(format: "price >= $expensivePrice")
let expensiveCars = cars.filteredArrayUsingPredicate(expensiveCarsPredicate.predicateWithSubstitutionVariables(["expensivePrice" : 45000]))
//: Between
let goodPriceCarsPredicate = NSPredicate(format: "price BETWEEN { 0, 30000 }")
let goodPriceCars = cars.filteredArrayUsingPredicate(goodPriceCarsPredicate)
//: Compound Predicates
// AND/OR
let goodPriceCarsFromGermanyPredicate = NSPredicate(format: "price BETWEEN { 0, 30000 } AND manufacturer.country = %@", germany)
let goodPriceCarsFromGermany = cars.filteredArrayUsingPredicate(goodPriceCarsFromGermanyPredicate)
// NSCompoundPredicate
let cheapCarsFromUsaPredicate = NSCompoundPredicate(type: .AndPredicateType, subpredicates: [usaPredicate, cheapCarsPredicate])
let cheapCarsFromUsa = cars.filteredArrayUsingPredicate(cheapCarsFromUsaPredicate)
//: String BEGINSWITH
// "name BEGINSWITH 'bó'" is case sensitive and without a glyph
// "name BEGINSWITH[c] 'bó'" is not case sensitive and without a glyph
// "name BEGINSWITH[cd] 'bó'" is not case sensitive and can have glyphs
let carsThatBeginsWithLetterBPredicate = NSPredicate(format: "name BEGINSWITH[cd] 'bó'")
let carsThatBeginsWithLetterB = cars.filteredArrayUsingPredicate(carsThatBeginsWithLetterBPredicate)
//: String CONTAINS
let carsWithLetterRPredicate = NSPredicate(format: "name CONTAINS[cd] 'r'")
let carsWithLetterR = cars.filteredArrayUsingPredicate(carsWithLetterRPredicate)
//: String ENDSWITH
let carsThatEndsWithLetterAPredicate = NSPredicate(format: "name ENDSWITH[cd] 'a'")
let carsThatEndsWithLetterA = cars.filteredArrayUsingPredicate(carsThatEndsWithLetterAPredicate)
//: String LIKE
let carsWithSTLettersPredicate = NSPredicate(format: "name LIKE[cd] 'M?ST*G'")
let carsWithSTLetters = cars.filteredArrayUsingPredicate(carsWithSTLettersPredicate)
//: String MATCHES
// ICU v3 Regular Expressions: http://userguide.icu-project.org/strings/regexp
let images: NSArray = ["top.png", "sprite001.png", "sprite002.png", "sprite003.png", "background.png"]
let spriteImagesPredicate = NSPredicate(format: "SELF MATCHES %@", "sprite\\d{3}.png") // has 3 numbers in the middle
let spriteImages = images.filteredArrayUsingPredicate(spriteImagesPredicate)
//: IN
let carsInListPredicate = NSPredicate(format: "name IN {'Golf','Boxster','Fiesta'}")
let carsInList = cars.filteredArrayUsingPredicate(carsInListPredicate)
//: Block Predicate
// Cannot be used for Core Data fetch requests backed by a SQLite store
let carsWithShortNamePredicate = NSPredicate { (car, _) -> Bool in
return car.name.characters.count <= 4
}
let carsWithShortName = cars.filteredArrayUsingPredicate(carsWithShortNamePredicate)
//: [Next](@next)
| mit | 2e959fbde5e95a686562c524ee1f374c | 35.727273 | 139 | 0.764026 | 3.835443 | false | false | false | false |
Eonil/EditorLegacy | Modules/EditorCommon/EditorCommon/UtilityAlgorithms/FilePath.swift | 1 | 1478 | //
// File.swift
// Editor
//
// Created by Hoon H. on 2015/01/11.
// Copyright (c) 2015 Eonil. All rights reserved.
//
import Foundation
///// Generates a user-friendly *name* for a data file.
///// Returns `nil` if a proper name cannot be made in short time.
//func generateUniqueUserFriendlyNameForNewFileAtParentDirectoryAtURL(u:NSURL) -> String? {
// return generateUniqueUserFriendlyNameWithPrefixAtParentDirectoryAtURL(u, prefixString: "New File")
//}
//
//
///// Generates a user-friendly *name* for a directory file.
///// Returns `nil` if a proper name cannot be made in short time.
//func generateUniqueUserFriendlyNameForNewFolderAtParentDirectoryAtURL(u:NSURL) -> String? {
// return generateUniqueUserFriendlyNameWithPrefixAtParentDirectoryAtURL(u, prefixString: "New Folder")
//}
/// Generates a user-friendly *name* for a new file.
/// Returns `nil` if a proper name cannot be made in short time.
func generateUniqueUserFriendlyNameWithPrefixAtParentDirectoryAtURL(u:NSURL, prefixString n:String) -> String? {
func isNameExists(base:NSURL, n:String) -> Bool {
let u = base.URLByAppendingPathComponent(n) // This will add ending slash if a directory at the path exists.
return u.existingAsDataFile || u.existingAsDirectoryFile
}
if isNameExists(u, n) == false {
return n
}
let MAX_TRIAL_COUNT = 256
for i in 1..<MAX_TRIAL_COUNT {
let n1 = n + " \(i)"
if isNameExists(u, n1) == false {
return n1
}
}
return nil
}
| mit | 9b6ed8dc7d84665bc81312de42e37ccd | 24.050847 | 112 | 0.719215 | 3.291759 | false | false | false | false |
ovenbits/ModelRocket | Sources/JSONTransformable.swift | 1 | 5841 | // JSONTransformable.swift
//
// Copyright (c) 2015 Oven Bits, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
#if os(iOS)
import UIKit
#endif
public protocol JSONTransformable {
associatedtype T
/// Extract object from JSON
static func fromJSON(json: JSON) -> T?
/// Convert object to JSON
func toJSON() -> AnyObject
}
// MARK: Default implementation for Model subclasses
extension JSONTransformable where Self: Model {
public static func fromJSON(json: JSON) -> Self? {
return Self.init(strictJSON: json)
}
public func toJSON() -> AnyObject {
return json().dictionary
}
}
// MARK: Default implementation for RawRepresentable types
extension JSONTransformable where Self: RawRepresentable, Self.RawValue == String {
public static func fromJSON(json: JSON) -> Self? {
return Self(rawValue: json.stringValue)
}
public func toJSON() -> AnyObject {
return rawValue
}
}
extension JSONTransformable where Self: RawRepresentable, Self.RawValue == Int {
public static func fromJSON(json: JSON) -> Self? {
return Self(rawValue: json.intValue)
}
public func toJSON() -> AnyObject {
return rawValue
}
}
// MARK: String
extension String: JSONTransformable {
public static func fromJSON(json: JSON) -> String? {
return json.string
}
public func toJSON() -> AnyObject {
return self
}
}
// MARK: NSDate
extension NSDate: JSONTransformable {
private class var JSONTransformableDateFormatter: NSDateFormatter {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
return dateFormatter
}
public class func fromJSON(json: JSON) -> NSDate? {
if let dateString = json.string {
return JSONTransformableDateFormatter.dateFromString(dateString)
}
return nil
}
public func toJSON() -> AnyObject {
return NSDate.JSONTransformableDateFormatter.stringFromDate(self)
}
}
// MARK: UIColor
#if os(iOS)
extension UIColor: JSONTransformable {
public class func fromJSON(json: JSON) -> UIColor? {
if let string = json.string {
var hexString = string
if (hexString.hasPrefix("#")) {
hexString = (hexString as NSString).substringFromIndex(1)
}
let scanner = NSScanner(string: hexString)
var hex: UInt32 = 0
scanner.scanHexInt(&hex)
let r = (hex >> 16) & 0xFF
let g = (hex >> 8) & 0xFF
let b = hex & 0xFF
return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1.0)
}
return nil
}
public func toJSON() -> AnyObject {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let hexString = NSString(format: "#%02x%02x%02x", Int(255*r),Int(255*g),Int(255*b)).uppercaseString
return hexString
}
}
#endif
// MARK: Bool
extension Bool: JSONTransformable {
public static func fromJSON(json: JSON) -> Bool? {
return json.bool
}
public func toJSON() -> AnyObject {
return self
}
}
// MARK: NSURL
extension NSURL: JSONTransformable {
public class func fromJSON(json: JSON) -> NSURL? {
return json.URL
}
public func toJSON() -> AnyObject {
return absoluteString
}
}
// MARK: NSNumber
extension NSNumber: JSONTransformable {
public class func fromJSON(json: JSON) -> NSNumber? {
return json.number
}
public func toJSON() -> AnyObject {
return self
}
}
// MARK: Double
extension Double: JSONTransformable {
public static func fromJSON(json: JSON) -> Double? {
return json.double
}
public func toJSON() -> AnyObject {
return self
}
}
// MARK: Float
extension Float: JSONTransformable {
public static func fromJSON(json: JSON) -> Float? {
return json.float
}
public func toJSON() -> AnyObject {
return self
}
}
// MARK: Int
extension Int: JSONTransformable {
public static func fromJSON(json: JSON) -> Int? {
return json.int
}
public func toJSON() -> AnyObject {
return self
}
}
// MARK: UInt
extension UInt: JSONTransformable {
public static func fromJSON(json: JSON) -> UInt? {
return json.uInt
}
public func toJSON() -> AnyObject {
return self
}
}
| mit | 05cf920bb3cded787fb31538bb684f51 | 25.917051 | 110 | 0.63876 | 4.418306 | false | false | false | false |
angelsteger/week2_carousel | week2/week2/TutorialScreensViewController.swift | 1 | 1852 | //
// TutorialScreensViewController.swift
// week2
//
// Created by Angel Steger on 9/27/15.
// Copyright © 2015 Angel Steger. All rights reserved.
//
import UIKit
class TutorialScreensViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var pageViewcontroller: UIPageControl!
@IBOutlet weak var horizontalScrollView: UIScrollView!
@IBOutlet weak var btn_TakeCarousel: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
horizontalScrollView.delegate = self
horizontalScrollView.contentSize = CGSize(width: 1280, height: 568)
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
// Get the current page based on the scroll offset
let page : Int = Int(round(scrollView.contentOffset.x / 320))
// Set the current page, so the dots will update
pageViewcontroller.currentPage = page
if page == 3 {
UIView.animateWithDuration(0.3, animations: {
self.btn_TakeCarousel.alpha = 1
})
}
else if page == 2 {
UIView.animateWithDuration(0.3, animations: {
self.btn_TakeCarousel.alpha = 0
})
}
}
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.
}
*/
}
| mit | 15d3ade61cb1fb13c069fb120c73f0e1 | 29.344262 | 106 | 0.646677 | 5.071233 | false | false | false | false |
BenziAhamed/Nevergrid | NeverGrid/Source/LevelZoneSystem.swift | 1 | 6510 | //
// LevelzoneSystem.swift
// MrGreen
//
// Created by Benzi on 23/08/14.
// Copyright (c) 2014 Benzi Ahamed. All rights reserved.
//
import Foundation
import SpriteKit
class LevelZoneSystem : System {
override init(_ world:WorldMapper) {
super.init(world)
world.eventBus.subscribe(GameEvent.GameEntitiesCreated, handler: self)
world.eventBus.subscribe(GameEvent.ZoneKeyCollected, handler: self)
if world.level.zoneBehaviour == ZoneBehaviour.Standalone {
world.eventBus.subscribe(GameEvent.PlayerMoveCompleted, handler: self)
}
}
override func handleEvent(event:Int, _ data:AnyObject?) {
switch event {
case GameEvent.ZoneKeyCollected:
let zoneKey = world.zoneKey.get(data as! Entity)
enableEntitiesForZone(zoneKey.zoneID, skipTurns:true)
makeZoneVisible(data as! Entity)
case GameEvent.GameEntitiesCreated:
var zoneLevel:UInt = 0
while zoneLevel <= world.level.initialZone {
world.level.activateCells(zoneLevel)
enableEntitiesForZone(zoneLevel)
zoneLevel++
}
case GameEvent.PlayerMoveCompleted:
pauseEnemiesIfPlayerEnteredNewZone()
default:
break
}
}
func makeZoneVisible(zoneKey:Entity) {
// make all cells that have current zone level visible
let zone = world.zoneKey.get(zoneKey)
for c in world.cell.entities() {
let location = world.location.get(c)
if world.level.cells.get(location)!.zone == zone.zoneID {
let sprite = world.sprite.get(c)
// appear from bottom
let rand = unitRandom() * world.gs.sideLength
let moveDown = SKAction.moveByX(0, y: -world.gs.sideLength-rand, duration: 0.0)
let fadeIn = SKAction.fadeInWithDuration(0.4)
let moveUp = SKAction.moveByX(0, y: +world.gs.sideLength+rand, duration: 0.5)
let animation = SKAction.sequence([
moveDown,
SKAction.group([fadeIn, moveUp])
])
fadeIn.timingMode = SKActionTimingMode.EaseIn
animation.timingMode = SKActionTimingMode.EaseOut
sprite.node.runAction(animation)
}
}
}
func enableEntitiesForZone(zoneID:UInt, skipTurns:Bool=false) {
// portals
for p in world.portal.entities() {
let portal = world.portal.get(p)
let start = world.location.get(p)
let sprite = world.sprite.get(p)
portal.enabled =
world.level.isActive(start) &&
world.level.isActive(portal.destination)
if !portal.enabled {
sprite.node.alpha = 0.0
} else {
sprite.node.runAction(SKAction.fadeInWithDuration(0.3))
}
}
// enemies
for e in world.enemy.entities() {
let enemy = world.enemy.get(e)
if enemy.enabled { continue } // ignore already enabled enemies
let location = world.location.get(e)
enemy.enabled = world.level.isActive(location)
// if we have just enabled an enemy for a zone level > initial zone level
// means that we are to show an enemy once the game is already in play
// and the entity landing controller has finished running long time ago
if enemy.enabled && zoneID > world.level.initialZone {
if skipTurns {
enemy.skipTurns = 1 // since we are just appearing, no need to make a move just yet
}
let sprite = world.sprite.get(e)
sprite.node.runAction(SKAction.fadeInWithDuration(0.7))
world.eventBus.raise(GameEvent.EnemyMadeVisibleForZone, data: e)
}
}
// goals
for e in world.goal.entities() {
let location = world.location.get(e)
if world.level.cells.get(location)!.zone == zoneID {
let sprite = world.sprite.get(e)
sprite.node.runAction(SKAction.fadeInWithDuration(0.3))
}
}
// powerups
for e in world.powerup.entities() {
let location = world.location.get(e)
if world.level.cells.get(location)!.zone == zoneID {
let sprite = world.sprite.get(e)
sprite.node.runAction(SKAction.fadeInWithDuration(0.3))
}
}
// zone keys
for e in world.zoneKey.entities() {
let location = world.location.get(e)
if world.level.cells.get(location)!.zone == zoneID {
let sprite = world.sprite.get(e)
sprite.node.runAction(SKAction.fadeInWithDuration(0.3))
}
}
}
/// when player enters a new zone in standalone mode,
/// we want the enemies to skip a move
func pauseEnemiesIfPlayerEnteredNewZone() {
let currentLocation = world.location.get(world.mainPlayer)
if !currentLocation.hasChanged() { return }
let currentZone = world.level.cells.get(currentLocation)!.zone
let previousZone = world.level.cells.get(currentLocation.previous())!.zone
if currentZone == previousZone { return }
// let player = world.player.get(world.mainPlayer)
// if !player.teleportedInLastMove { return }
// if the players zone has changed
for e in world.enemy.entities() {
let enemy = world.enemy.get(e)
let enemyLocation = world.location.get(e)
let enemyZone = world.level.cells.get(enemyLocation)!.zone
if enemyZone == currentZone {
// println("player previous location = \(currentLocation.previous())")
// println("player current location = \(currentLocation)")
// println("player location changed? = \(currentLocation.hasChanged())")
// println("zone: \(currentZone) - enemy:\(e.id) - should skip a move")
enemy.skipTurns = 1
}
}
}
} | isc | 32a9dbd67fad744415b4e7502c818c64 | 36.205714 | 103 | 0.555914 | 4.680086 | false | false | false | false |
MoralAlberto/SlackWebAPIKit | SlackWebAPIKit/Classes/Domain/UseCases/Users/FindUserAndPostMessageUseCase.swift | 1 | 1083 | import Foundation
import RxSwift
public protocol FindUserAndPostMessageUseCaseProtocol: class {
func execute(text: String, user: String) -> Observable<Bool>
}
public class FindUserAndPostMessageUseCase: FindUserAndPostMessageUseCaseProtocol {
let findUserUseCase: FindUserUseCaseProtocol
let postMessageUseCase: PostMessageUseCaseProtocol
public init(findUserUseCase: FindUserUseCaseProtocol = FindUserUseCase(),
postMessageUseCase: PostMessageUseCaseProtocol = PostMessageUseCase()) {
self.findUserUseCase = findUserUseCase
self.postMessageUseCase = postMessageUseCase
}
public func execute(text: String, user: String) -> Observable<Bool> {
return findUserUseCase.execute(user: user).flatMap { [weak self] foundUser -> Observable<Bool> in
guard let strongSelf = self,
let userId = foundUser.id
else {
return Observable.just(false)
}
return strongSelf.postMessageUseCase.execute(text: text, channel: userId)
}
}
}
| mit | df68ee1866caaa61429dd6e8e47b194f | 37.678571 | 105 | 0.696214 | 4.96789 | false | false | false | false |
boytpcm123/ImageDownloader | ImageDownloader/ImageDownloader/PhotoImport.swift | 1 | 1996 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
PhotoImport represents the import operation of a Photo. It combines both the PhotoDownload and PhotoFilter operations.
*/
import UIKit
class PhotoImport: NSObject, ProgressReporting {
// MARK: Properties
var completionHandler: ((_ data: Data?, _ error: NSError?) -> Void)?
let progress: Progress
let download: PhotoDownload
// MARK: Initializers
init(URL: Foundation.URL) {
progress = Progress()
/*
This progress's children are weighted: The download takes up 90%
and the filter takes the remaining portion.
*/
progress.totalUnitCount = 10
download = PhotoDownload(URL: URL)
}
func start() {
/*
Use explicit composition to add the download's progress to ours,
taking 9/10 units.
*/
progress.addChild(download.progress, withPendingUnitCount: 9)
download.completionHandler = { data, error in
guard let data = data else {
self.callCompletionHandler(data: nil, error: error)
return
}
/*
Make self.progress the currentProgress. Since the filteredImage
supports implicit progress reporting, it will add its progress
to ours.
*/
// self.progress.becomeCurrent(withPendingUnitCount: 1)
// let filteredImage = PhotoFilter.filteredImage(image)
// self.progress.resignCurrent()
self.callCompletionHandler(data: data, error: nil)
}
download.start()
}
fileprivate func callCompletionHandler(data: Data?, error: NSError?) {
completionHandler?(data, error)
completionHandler = nil
}
}
| apache-2.0 | b418626c0274b01dc68bbb6cc7e51139 | 28.104478 | 134 | 0.593846 | 4.97449 | false | false | false | false |
cruisediary/Pastel | Sources/Pastel/Classes/PastelView.swift | 1 | 3791 | //
// PastelView.swift
// Pastel
//
// Created by Cruz on 05/05/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
open class PastelView: UIView {
private struct Animation {
static let keyPath = "colors"
static let key = "ColorChange"
}
//MARK: - Custom Direction
open var startPoint: CGPoint = PastelPoint.topRight.point
open var endPoint: CGPoint = PastelPoint.bottomLeft.point
open var startPastelPoint = PastelPoint.topRight {
didSet {
startPoint = startPastelPoint.point
}
}
open var endPastelPoint = PastelPoint.bottomLeft {
didSet {
endPoint = endPastelPoint.point
}
}
//MARK: - Custom Duration
open var animationDuration: TimeInterval = 5.0
fileprivate let gradient = CAGradientLayer()
private var currentGradient: Int = 0
private var colors: [UIColor] = [UIColor(red: 156/255, green: 39/255, blue: 176/255, alpha: 1.0),
UIColor(red: 255/255, green: 64/255, blue: 129/255, alpha: 1.0),
UIColor(red: 123/255, green: 31/255, blue: 162/255, alpha: 1.0),
UIColor(red: 32/255, green: 76/255, blue: 255/255, alpha: 1.0),
UIColor(red: 32/255, green: 158/255, blue: 255/255, alpha: 1.0),
UIColor(red: 90/255, green: 120/255, blue: 127/255, alpha: 1.0),
UIColor(red: 58/255, green: 255/255, blue: 217/255, alpha: 1.0)]
public override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
}
open override func layoutSubviews() {
super.layoutSubviews()
gradient.frame = bounds
}
public func startAnimation() {
gradient.removeAllAnimations()
setup()
animateGradient()
}
fileprivate func setup() {
gradient.frame = bounds
gradient.colors = currentGradientSet()
gradient.startPoint = startPoint
gradient.endPoint = endPoint
gradient.drawsAsynchronously = true
layer.insertSublayer(gradient, at: 0)
}
fileprivate func currentGradientSet() -> [CGColor] {
guard colors.count > 0 else { return [] }
return [colors[currentGradient % colors.count].cgColor,
colors[(currentGradient + 1) % colors.count].cgColor]
}
public func setColors(_ colors: [UIColor]) {
guard colors.count > 0 else { return }
self.colors = colors
}
public func setPastelGradient(_ gradient: PastelGradient) {
setColors(gradient.colors())
}
public func addcolor(_ color: UIColor) {
self.colors.append(color)
}
func animateGradient() {
currentGradient += 1
let animation = CABasicAnimation(keyPath: Animation.keyPath)
animation.duration = animationDuration
animation.toValue = currentGradientSet()
animation.fillMode = .forwards
animation.isRemovedOnCompletion = false
animation.delegate = self
gradient.add(animation, forKey: Animation.key)
}
open override func removeFromSuperview() {
super.removeFromSuperview()
gradient.removeAllAnimations()
gradient.removeFromSuperlayer()
}
}
extension PastelView: CAAnimationDelegate {
public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if flag {
gradient.colors = currentGradientSet()
animateGradient()
}
}
}
| mit | 4b1b003867a6e836715a03fcd8221177 | 29.079365 | 101 | 0.59657 | 4.627595 | false | false | false | false |
Feverup/braintree_ios | UITests/Helpers/BTUITest.swift | 1 | 1657 | import XCTest
extension XCTestCase {
func waitForElementToAppear(element: XCUIElement, timeout: NSTimeInterval = 10, file: String = #file, line: UInt = #line) {
let existsPredicate = NSPredicate(format: "exists == true")
expectationForPredicate(existsPredicate,
evaluatedWithObject: element, handler: nil)
waitForExpectationsWithTimeout(timeout) { (error) -> Void in
if (error != nil) {
let message = "Failed to find \(element) after \(timeout) seconds."
self.recordFailureWithDescription(message, inFile: file, atLine: line, expected: true)
}
}
}
func waitForElementToBeHittable(element: XCUIElement, timeout: NSTimeInterval = 10, file: String = #file, line: UInt = #line) {
let existsPredicate = NSPredicate(format: "exists == true && hittable == true")
expectationForPredicate(existsPredicate,
evaluatedWithObject: element, handler: nil)
waitForExpectationsWithTimeout(timeout) { (error) -> Void in
if (error != nil) {
let message = "Failed to find \(element) after \(timeout) seconds."
self.recordFailureWithDescription(message, inFile: file, atLine: line, expected: true)
}
}
}
}
extension XCUIElement {
func forceTapElement() {
if self.hittable {
self.tap()
} else {
let coordinate: XCUICoordinate = self.coordinateWithNormalizedOffset(CGVectorMake(0.0, 0.0))
coordinate.tap()
}
}
} | mit | 1fa362ed610fac777ec787dffd791e67 | 38.47619 | 132 | 0.590827 | 5.051829 | false | false | false | false |
apple/swift | validation-test/compiler_crashers_fixed/01230-swift-constraints-constraintsystem-gettypeofmemberreference.swift | 65 | 636 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func c<g>() -> (g, g -> g) -> g {
d b d.f = {
}
{
g) {
i }
}
i c {
}
class d: c{ class func f {}
protocol A {
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
}
struct c<d, e: b where d.c == e> {
}
func a(b: Int = 0) {
}
let c = a
| apache-2.0 | 0cd90858739aba9e8bab2e8ff21deeb2 | 20.931034 | 79 | 0.632075 | 2.789474 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/HotelsSource/Filters/CustomFilterViews/Root/RootFilterView.swift | 1 | 1544 | import UIKit
class RootFilterView: UIView, FilterViewCellDelegate {
var tableWidth: CGFloat?
private (set) var contentContainer: UIView!
func nibName() -> String {
return String(describing: type(of: self))
}
func allFilterCells() -> [RootFilterViewCell] {
return []
}
private (set) var filter: Filter!
override func awakeFromNib() {
super.awakeFromNib()
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
private func initialize() {
let view = loadViewFromNib(nibName(), self)!
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.clear
addSubview(view)
view.autoPinEdgesToSuperviewEdges()
contentContainer = view
}
func configure(with filter: Filter) {
self.filter = filter
for i in 0..<allFilterCells().count {
let cell = allFilterCells()[i]
cell.isSelected = cellShouldBeSelected(cell: cell)
cell.delegate = self
}
}
func filterViewCellPressed(filterViewCell: RootFilterViewCell) {
filterViewCell.isSelected = !filterViewCell.isSelected
}
func cellShouldBeSelected(cell: RootFilterViewCell) -> Bool {
return false
}
class func height(for tableWidth: CGFloat, with filter: Filter) -> CGFloat {
return 0
}
}
| mit | ef9b362cac6f933eec24e958c0a05e89 | 23.507937 | 80 | 0.627591 | 4.809969 | false | false | false | false |
avaidyam/Parrot | Parrot/PersonIndicatorViewController.swift | 1 | 4274 | import MochaUI
import Contacts
import ContactsUI
import ParrotServiceExtension
// away vs here == alphaValue of toolbar item
// typing == hidden value of tooltipcontroller messageprogressview
/// TODO: this class isn't very composable yet...
public class PersonIndicatorViewController: NSViewController {
public static let contactStore = CNContactStore()
public lazy var toolbarItem: NSToolbarItem = {
assert(self.person != nil, "Cannot create a toolbar item without an assigned person!")
let i = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier(rawValue: self.person!.identifier))
i.visibilityPriority = .high
i.view = self.view
i.label = self.person?.fullName ?? ""
return i
}()
public var person: Person? {
didSet {
guard self.person != nil else { return }
self.identifier = NSUserInterfaceItemIdentifier(rawValue: self.person!.identifier)
(self.view as? NSButton)?.image = self.person!.image
self.cacheContact()
}
}
private var contact: CNContact! = nil
public var isDimmed: Bool = false {
didSet {
UI {
self.view.animator().alphaValue = self.isDimmed ? 0.6 : 1.0
}
}
}
public override func loadView() {
let b = NSButton(title: "", target: self, action: #selector(PersonIndicatorViewController.buttonPressed(_:)))
b.isBordered = false
b.wantsLayer = true
b.layer!.cornerRadius = 16
b.frame.size.width = 32
self.view = b
}
public override func viewDidLayout() {
self.view.trackingAreas.forEach {
self.view.removeTrackingArea($0)
}
let trackingArea = NSTrackingArea(rect: self.view.frame,
options: [.activeAlways, .mouseEnteredAndExited],
owner: self, userInfo: nil)
self.view.addTrackingArea(trackingArea)
}
// Cache the associated CNContact for the person.
private func cacheContact() {
let request = CNContactFetchRequest(keysToFetch: [CNContactViewController.descriptorForRequiredKeys()])
request.predicate = CNContact.predicateForContacts(matchingName: self.person?.fullName ?? "")
DispatchQueue.global(qos: .background).async { [weak self] in
do {
try PersonIndicatorViewController.contactStore.enumerateContacts(with: request) { [weak self] c, stop in
stop.pointee = true
self?.contact = c
}
} catch {
self?.contact = CNContact()
}
}
}
@objc dynamic public func buttonPressed(_ sender: NSButton!) {
PersonIndicatorToolTipController.popover.performClose(nil)
let cv = CNContactViewController()
cv.contact = self.contact
cv.preferredContentSize = CGSize(width: 300, height: 400)
self.presentViewController(cv, asPopoverRelativeTo: self.view.bounds,
of: self.view, preferredEdge: .maxY,
behavior: .transient)
// The VC shows up offset so it's important to adjust it.
cv.view.frame.origin.x -= 40.0
cv.view.frame.size.width += 52.0
}
public override func mouseEntered(with event: NSEvent) {
guard let vc = PersonIndicatorToolTipController.popover.contentViewController
as? PersonIndicatorToolTipController else { return }
var prefix = ""
switch self.person?.reachability ?? .unavailable {
case .unavailable: break
case .phone: prefix = "📱 "
case .tablet: prefix = "📱 " //💻
case .desktop: prefix = "🖥 "
}
_ = vc.view // loadView()
vc.text?.stringValue = prefix + (self.person?.fullName ?? "")
PersonIndicatorToolTipController.popover.show(relativeTo: view.bounds, of: view, preferredEdge: .maxY)
}
public override func mouseExited(with event: NSEvent) {
PersonIndicatorToolTipController.popover.performClose(nil)
}
}
| mpl-2.0 | ea62638c774601bc548078ec61df8e82 | 36.716814 | 120 | 0.599718 | 4.984795 | false | false | false | false |
6ag/WeiboSwift-mvvm | WeiboSwift/Classes/View/Main/VisitorView.swift | 1 | 4195 | //
// VisitorView.swift
// WeiboSwift
//
// Created by zhoujianfeng on 2017/1/16.
// Copyright © 2017年 周剑峰. All rights reserved.
//
import UIKit
import SnapKit
/// 访客视图
class VisitorView: UIView {
/// 访客视图信息
var visitorInfo: [String: String]? {
didSet {
guard let imageName = visitorInfo?["imageName"],
let message = visitorInfo?["message"] else {
return
}
tipLabel.text = message
// 首页不修改图片
if imageName.isEmpty {
startAnimation()
return
}
bgImageView.image = UIImage(named: imageName)
hourseImageView.isHidden = true
grayImageView.isHidden = true
}
}
override init(frame: CGRect) {
super.init(frame: frame)
prepareUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 添加旋转动画
private func startAnimation() {
let anim = CABasicAnimation(keyPath: "transform.rotation")
anim.toValue = 2 * M_PI
anim.repeatCount = MAXFLOAT
anim.duration = 15
anim.isRemovedOnCompletion = false
bgImageView.layer.add(anim, forKey: nil)
}
// MARK: - 懒加载
/// 灰色背景图
fileprivate lazy var grayImageView: UIImageView = UIImageView(
image: UIImage(named: "visitordiscover_feed_mask_smallicon"))
/// 转圈的背景图
fileprivate lazy var bgImageView: UIImageView = UIImageView(
image: UIImage(named: "visitordiscover_feed_image_smallicon"))
/// 房子
fileprivate lazy var hourseImageView: UIImageView = UIImageView(
image: UIImage(named: "visitordiscover_feed_image_house"))
/// 提示文字
fileprivate lazy var tipLabel: UILabel = UILabel.cz_label(
withText: "关注一些人,回这里看看有什么惊喜。关注一些人,回这里看看有什么惊喜",
fontSize: 14,
color: UIColor.darkGray)
/// 注册按钮
public lazy var registerButton: UIButton = UIButton.cz_textButton(
"注册",
fontSize: 16,
normalColor: UIColor.orange,
highlightedColor: UIColor.black,
backgroundImageName: "common_button_white_disable")
/// 登录按钮
public lazy var loginButton: UIButton = UIButton.cz_textButton(
"登录",
fontSize: 16,
normalColor: UIColor.orange,
highlightedColor: UIColor.black,
backgroundImageName: "common_button_white_disable")
}
// MARK: - 设置界面
extension VisitorView {
/// 准备UI
fileprivate func prepareUI() {
backgroundColor = UIColor.cz_color(withHex: 0xEDEDED)
tipLabel.preferredMaxLayoutWidth = UIScreen.cz_screenWidth() - 80
tipLabel.numberOfLines = 0
addSubview(bgImageView)
addSubview(grayImageView)
addSubview(hourseImageView)
addSubview(tipLabel)
addSubview(registerButton)
addSubview(loginButton)
bgImageView.snp.makeConstraints { (make) in
make.center.equalTo(self)
}
grayImageView.snp.makeConstraints { (make) in
make.center.equalTo(self)
}
hourseImageView.snp.makeConstraints { (make) in
make.center.equalTo(self)
}
tipLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(self)
make.top.equalTo(bgImageView.snp.bottom).offset(20)
}
registerButton.snp.makeConstraints { (make) in
make.centerX.equalTo(self).offset(-80)
make.top.equalTo(tipLabel.snp.bottom).offset(20)
make.size.equalTo(CGSize(width: 120, height: 45))
}
loginButton.snp.makeConstraints { (make) in
make.centerX.equalTo(self).offset(80)
make.top.equalTo(tipLabel.snp.bottom).offset(20)
make.size.equalTo(CGSize(width: 120, height: 45))
}
}
}
| mit | 8c5ff3489b73cfae275771d31f4c0d00 | 28.182482 | 73 | 0.589295 | 4.698002 | false | false | false | false |
atl009/WordPress-iOS | WordPress/Classes/Extensions/String+RegEx.swift | 1 | 2849 | import Foundation
// MARK: - String: RegularExpression Helpers
//
extension String {
/// Find all matches of the specified regex.
///
/// - Parameters:
/// - regex: the regex to use.
/// - options: the regex options.
///
/// - Returns: the requested matches.
///
func matches(regex: String, options: NSRegularExpression.Options = []) -> [NSTextCheckingResult] {
let regex = try! NSRegularExpression(pattern: regex, options: options)
let fullRange = NSRange(location: 0, length: count)
return regex.matches(in: self, options: [], range: fullRange)
}
/// Replaces all matches of a given RegEx, with a template String.
///
/// - Parameters:
/// - regex: the regex to use.
/// - template: the template string to use for the replacement.
/// - options: the regex options.
///
/// - Returns: a new string after replacing all matches with the specified template.
///
func replacingMatches(of regex: String, with template: String, options: NSRegularExpression.Options = []) -> String {
let regex = try! NSRegularExpression(pattern: regex, options: options)
let fullRange = NSRange(location: 0, length: count)
return regex.stringByReplacingMatches(in: self,
options: [],
range: fullRange,
withTemplate: template)
}
/// Replaces all matches of a given RegEx using a provided block.
///
/// - Parameters:
/// - regex: the regex to use for pattern matching.
/// - options: the regex options.
/// - block: the block that will be used for the replacement logic.
///
/// - Returns: the new string.
///
func replacingMatches(of regex: String, options: NSRegularExpression.Options = [], using block: (String, [String]) -> String) -> String {
let regex = try! NSRegularExpression(pattern: regex, options: options)
let fullRange = NSRange(location: 0, length: count)
let matches = regex.matches(in: self, options: [], range: fullRange)
var newString = self
for match in matches.reversed() {
let matchRange = range(from: match.range)
let matchString = substring(with: matchRange)
var submatchStrings = [String]()
for submatchIndex in 0 ..< match.numberOfRanges {
let submatchRange = self.range(from: match.rangeAt(submatchIndex))
let submatchString = self.substring(with: submatchRange)
submatchStrings.append(submatchString)
}
newString.replaceSubrange(matchRange, with: block(matchString, submatchStrings))
}
return newString
}
}
| gpl-2.0 | d1cff32feb9bafdf4d08ed929c6fe3a5 | 36 | 141 | 0.593191 | 4.853492 | false | false | false | false |
caopengxu/scw | scw/scw/Code/Tool/FrameCircle/PXCustomLabel.swift | 1 | 650 | //
// PXCustomLabel.swift
// scw
//
// Created by cpx on 2017/7/15.
// Copyright © 2017年 scw. All rights reserved.
//
import UIKit
@IBDesignable
class PXCustomLabel: MyLabelFont {
@IBInspectable var borderWidth: CGFloat = 0.0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: UIColor = UIColor() {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var cornerRadius: CGFloat = 0.0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = true
}
}
}
| mit | b742ce0b12e183d22a30de2b121e3838 | 18.606061 | 57 | 0.574961 | 4.371622 | false | false | false | false |
bsmith11/ScoreReporter | ScoreReporter/Settings/SettingsViewController.swift | 1 | 6319 | //
// SettingsViewController.swift
// ScoreReporter
//
// Created by Bradley Smith on 10/4/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
import UIKit
import Anchorage
import ScoreReporterCore
class SettingsViewController: UIViewController, MessageDisplayable {
fileprivate let dataSource: SettingsDataSource
fileprivate let tableView = UITableView(frame: .zero, style: .plain)
fileprivate let headerView = SettingsHeaderView(frame: .zero)
fileprivate var loginButton: UIBarButtonItem?
fileprivate var logoutButton: UIBarButtonItem?
override var topLayoutGuide: UILayoutSupport {
configureMessageView(super.topLayoutGuide)
return messageLayoutGuide
}
init(dataSource: SettingsDataSource) {
self.dataSource = dataSource
super.init(nibName: nil, bundle: nil)
title = "Settings"
let image = UIImage(named: "icn-settings")
let selectedImage = UIImage(named: "icn-settings-selected")
tabBarItem = UITabBarItem(title: title, image: image, selectedImage: selectedImage)
tabBarItem.imageInsets = UIEdgeInsets(top: 5.5, left: 0.0, bottom: -5.5, right: 0.0)
let backButton = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backButton
loginButton = UIBarButtonItem(title: "Login", style: .plain, target: self, action: #selector(loginButtonPressed))
logoutButton = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(logoutButtonPressed))
if let _ = User.currentUser {
navigationItem.rightBarButtonItem = logoutButton
}
else {
navigationItem.rightBarButtonItem = loginButton
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func loadView() {
view = UIView()
configureViews()
configureLayout()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let _ = User.currentUser {
let size = headerView.size(with: tableView.bounds.width)
headerView.frame = CGRect(origin: .zero, size: size)
tableView.tableHeaderView = headerView
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
deselectRows(in: tableView, animated: animated)
}
}
// MARK: - Private
private extension SettingsViewController {
func configureViews() {
tableView.dataSource = self
tableView.delegate = self
tableView.register(cellClass: SettingsCell.self)
tableView.estimatedRowHeight = 70.0
tableView.rowHeight = UITableViewAutomaticDimension
tableView.backgroundColor = UIColor.white
tableView.separatorStyle = .none
tableView.alwaysBounceVertical = true
view.addSubview(tableView)
if let user = User.currentUser {
headerView.configure(with: user)
}
}
func configureLayout() {
tableView.edgeAnchors == edgeAnchors
}
@objc func loginButtonPressed() {
let loginViewModel = LoginViewModel()
let loginViewController = LoginViewController(viewModel: loginViewModel)
loginViewController.delegate = self
let loginNavigationController = BaseNavigationController(rootViewController: loginViewController)
present(loginNavigationController, animated: true, completion: nil)
}
@objc func logoutButtonPressed() {
let alertController = UIAlertController(title: "Logout", message: "Are you sure you want to logout?", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let logoutAction = UIAlertAction(title: "Logout", style: .destructive) { [weak self] _ in
self?.navigationItem.rightBarButtonItem = self?.loginButton
let loginService = LoginService(client: APIClient.sharedInstance)
loginService.logout()
self?.tableView.tableHeaderView = nil
}
alertController.addAction(cancelAction)
alertController.addAction(logoutAction)
present(alertController, animated: true, completion: nil)
}
}
// MARK: - UITableViewDataSource
extension SettingsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return dataSource.numberOfSections()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.numberOfItems(in: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueCell(for: indexPath) as SettingsCell
let item = dataSource.item(at: indexPath)
cell.configure(with: item)
cell.separatorHidden = indexPath.item == 0
return cell
}
}
// MARK: - UITableViewDelegate
extension SettingsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let item = dataSource.item(at: indexPath) else {
return
}
switch item {
case .acknowledgements:
let acknowledgementListDataSource = AcknowledgementListDataSource()
let acknowledgementListViewController = AcknowledgementListViewController(dataSource: acknowledgementListDataSource)
navigationController?.pushViewController(acknowledgementListViewController, animated: true)
default:
break
}
}
}
// MARK: - LoginViewControllerDelegate
extension SettingsViewController: LoginViewControllerDelegate {
func didLogin(in controller: LoginViewController) {
navigationItem.rightBarButtonItem = logoutButton
if let user = User.currentUser {
headerView.configure(with: user)
view.setNeedsLayout()
view.layoutIfNeeded()
}
}
}
| mit | da21111f7ce11458069944289d93f261 | 32.428571 | 133 | 0.671257 | 5.527559 | false | false | false | false |
czerenkow/LublinWeather | App/Settings Languages/SettingsLanguageInteractor.swift | 1 | 1540 | //
// SettingsLanguageInteractor.swift
// LublinWeather
//
// Created by Damian Rzeszot on 03/05/2018.
// Copyright © 2018 Damian Rzeszot. All rights reserved.
//
import Foundation
final class SettingsLanguageInteractor: Interactor {
weak var router: SettingsLanguageRouter!
weak var presenter: SettingsLanguagePresentable!
var service: SettingsLanguageService! = SettingsLanguageService()
// MARK: -
var tracker: Tracker<SettingsLanguageEvent>!
// MARK: -
override func activate() {
super.activate()
tracker.track(.activate)
refresh()
}
override func deactivate() {
super.deactivate()
tracker.track(.deactivate)
}
private func refresh() {
let model = SettingsLanguageViewModel(availables: service.available(), active: service.get()[0])
presenter.configure(with: model)
}
}
extension SettingsLanguageInteractor: SettingsLanguageOutput {
func select(_ index: Int) {
let code = service.available()[index]
tracker.track(.select(code))
presenter.alert(language: code) { result in
self.tracker.track(.confirm(result))
if result {
self.service.set(languages: [code])
self.refresh()
}
}
}
}
extension SettingsLanguageViewModel {
init(availables: [String], active: String) {
self.entries = availables.map { .init(identifier: $0) }
self.active = availables.index(of: active) ?? 0
}
}
| mit | b010eed84409a1504754cc02fccd3e1b | 20.375 | 104 | 0.632878 | 4.435159 | false | false | false | false |
benlangmuir/swift | test/Interpreter/type_wrapper_with_actors.swift | 2 | 1553 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -target %target-cpu-apple-macosx10.15 -enable-experimental-feature TypeWrappers -parse-as-library -emit-library -emit-module-path %t/type_wrapper_defs.swiftmodule -module-name type_wrapper_defs %S/Inputs/type_wrapper_defs.swift -o %t/%target-library-name(type_wrapper_defs)
// RUN: %target-build-swift -target %target-cpu-apple-macosx10.15 -ltype_wrapper_defs -module-name main -I %t -L %t %s -o %t/main %target-rpath(%t)
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main %t/%target-library-name(type_wrapper_defs) | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: asserts
// REQUIRES: concurrency
// rdar://76038845
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
// REQUIRES: OS=macosx
// This requires executable tests to be run on the same machine as the compiler,
// as it links with a dylib that it doesn't arrange to get uploaded to remote executors.
// (rdar://99051588)
// UNSUPPORTED: remote_run || device_run
import type_wrapper_defs
@Wrapper
public actor Actor {
public var name: String
@PropWrapper public var age: Int? = nil
public func setAge(_ newAge: Int) async {
age = newAge
}
}
let a = Actor(name: "Arhtur Dent")
await print(a.name)
// CHECK: in getter
// CHECK-NEXT: Arhtur Dent
await print(a.age)
// CHECK: in getter
// CHECK-NEXT: nil
await a.setAge(30)
// CHECK: in getter
// CHECK-NEXT: in setter => PropWrapper<Optional<Int>>(value: Optional(30))
await print(a.age)
// CHECK: in getter
// CHECK-NEXT: 30
| apache-2.0 | 70ae9e5afbcd2c5239569a1e1cef597a | 31.354167 | 301 | 0.716677 | 3.162933 | false | false | false | false |
zon/that-bus | ios/That Bus/TicketsController.swift | 1 | 2312 | import Foundation
import UIKit
import PromiseKit
class TicketsController : UIViewController {
let layout = TicketsLayout()
private var group: TicketGroup?
required init() {
super.init(nibName: nil, bundle: nil)
title = "Tickets"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = layout
layout.quantity.button.addTarget(self, action: #selector(groupTouch), for: .touchUpInside)
}
override func viewWillAppear(_ animated: Bool) {
layout.setInsets(top: navigationController?.navigationBar.frame.maxY, bottom: tabBarController?.tabBar.frame.height)
}
override func viewDidAppear(_ animated: Bool) {
progress(
Session
.getUser()
.then { _ in when(fulfilled: Product.get(), Ticket.get()) }
.then { products, tickets -> Void in
if let product = products.first {
let group = TicketGroup(product: product, tickets: tickets)
self.group = group
self.layout.update(group: group)
} else {
self.group = nil
AlertController.show(message: "No tickets found.")
}
}
)
}
func groupTouch() {
if let group = group, let navigation = navigationController {
if let ticket = group.active {
navigation.pushViewController(TicketController(product: group.product, ticket: ticket), animated: true)
} else if group.hasTickets {
progress(Ticket.activate().then { ticket -> Void in
navigation.pushViewController(TicketController(product: group.product, ticket: ticket), animated: true)
})
} else {
progress(Session.getUser().then { user -> Void in
let controller = CheckoutController(user: user, product: group.product)
navigation.pushViewController(controller, animated: true)
})
}
}
}
}
| gpl-3.0 | fc1763a9f77e89e16e44695a773358d2 | 33.507463 | 124 | 0.539792 | 5.401869 | false | false | false | false |
nheagy/WordPress-iOS | WordPress/Classes/ViewRelated/People/PeopleCellViewModel.swift | 1 | 887 | import Foundation
import WordPressShared
struct PeopleCellViewModel {
let displayName: String
let username: String
let role: Person.Role
let superAdmin: Bool
let avatarURL: NSURL?
init(person: Person) {
self.displayName = person.displayName
self.username = person.username
self.role = person.role
self.superAdmin = person.isSuperAdmin
self.avatarURL = person.avatarURL
}
var usernameText: String {
return "@" + username
}
var roleBorderColor: UIColor {
return role.color()
}
var roleBackgroundColor: UIColor {
return role.color()
}
var roleTextColor: UIColor {
return WPStyleGuide.People.RoleBadge.textColor
}
var roleText: String {
return role.localizedName()
}
var superAdminHidden: Bool {
return !superAdmin
}
}
| gpl-2.0 | 5fe0befc1f172af6bf313d6b7d7b8643 | 20.119048 | 54 | 0.636979 | 4.846995 | false | false | false | false |
adrfer/swift | test/Constraints/recursive_concrete_constraints.swift | 12 | 604 | // RUN: %target-parse-verify-swift
struct S<A: CollectionType where A.Index == Int> : CollectionType {
typealias Element = A.Generator.Element
typealias Index = A.Index
init(base: A, baseRange: Range<Index>) {
self.base = base
self.baseRange = baseRange
}
var startIndex: Index {
return Int(0)
}
var endIndex: Index {
return baseRange.count
}
subscript(i: Index) -> Element {
return base[baseRange.startIndex + i]
}
func generate() -> IndexingGenerator<S> {
return IndexingGenerator(self)
}
var base: A
var baseRange: Range<A.Index>
}
| apache-2.0 | 64fd4764c6a29e12fb38c05564da4e8e | 19.133333 | 67 | 0.652318 | 3.682927 | false | false | false | false |
KoCMoHaBTa/MHAppKit | MHAppKit/Extensions/UIKit/UIImagePickerController/UIImagePickerControllerMediaInfo+Properties.swift | 1 | 4519 | //
// UIImagePickerControllerMediaInfo+Properties.swift
// MHAppKit
//
// Created by Milen Halachev on 18.01.19.
// Copyright © 2019 Milen Halachev. All rights reserved.
//
#if canImport(UIKit) && canImport(Photos)
import Foundation
import UIKit
import MobileCoreServices
import Photos
@available(tvOS, unavailable)
extension Dictionary where Key == UIImagePickerController.InfoKey, Value == Any {
///The media type selected by the user. The value of this property is a type code such as kUTTypeImage or kUTTypeMovie.
public var mediaType: String? {
return self[.mediaType] as? String
}
///The original, uncropped image selected by the user.
public var originalImage: UIImage? {
return self[.originalImage] as? UIImage
}
///Specifies an image edited by the user.
public var editedImage: UIImage? {
return self[.editedImage] as? UIImage
}
///Specifies the cropping rectangle that was applied to the original image.
public var cropRect: CGRect? {
return (self[.cropRect] as? NSValue)?.cgRectValue
}
///Specifies the filesystem URL for the movie.
public var mediaURL: URL? {
return self[.mediaURL] as? URL
}
///The Assets Library URL for the original version of the picked item. After the user edits a picked item—such as by cropping an image or trimming a movie—the URL continues to point to the original version of the picked item.
@available(iOS, deprecated: 11.0, message: "Use `asset` instead.")
public var referenceURL: URL? {
return self[.referenceURL] as? URL
}
///Metadata for a newly-captured photograph. This key is valid only when using an image picker whose source type is set to camera, and applies only to still images.
public var mediaMetadata: [String: Any]? {
return self[.mediaMetadata] as? [String: Any]
}
///The Live Photo representation of the selected or captured photo. Include the kUTTypeImage and kUTTypeLivePhoto identifiers in the allowed media types when configuring an image picker controller.
@available(tvOS 10, *)
@available(iOS 9.1, *)
public var livePhoto: PHLivePhoto? {
return self[.livePhoto] as? PHLivePhoto
}
@available(tvOS 10, *)
@available(iOS 11.0, *)
///The key to use when retrieving a Photos asset for the image.
public var asset: PHAsset? {
return self[.phAsset] as? PHAsset
}
}
@available(tvOS, unavailable)
extension Dictionary where Key == UIImagePickerController.InfoKey, Value == Any {
///True if the media type is image, otherwise false.
public var isImage: Bool {
return self.mediaType == kUTTypeImage as String
}
///True if the media type is movie, otherwise false.
public var isMovie: Bool {
return self.mediaType == kUTTypeMovie as String
}
}
@available(tvOS, unavailable)
extension Dictionary where Key == UIImagePickerController.InfoKey, Value == Any {
///The asset representation of the media. Loaded using the .phAsset key (iOS 11+) or referenceURL (prior iOS 11)
@available(tvOS 10, *)
public func fetchAsset() -> PHAsset? {
return self.asset
}
}
@available(tvOS, unavailable)
extension Dictionary where Key == UIImagePickerController.InfoKey, Value == Any {
/**
Loads the media metadata if the recever.
The implementation loads the metadata in the followin way:
- checks if metadata is available in the info using `UIImagePickerControllerMediaMetadata` - this is available if the media is captured image.
- if above is not available - loads metada from the asset representation of the receiver - this is available if the media is selected image from photo library.
- warning: Video and Live Photos are not tested
*/
@available(tvOS 10, *)
public func mediaMetadata(_ completion: @escaping ([AnyHashable: Any]?) -> Void) {
//TODO: Test and update behaviour for videos and live photos
if let mediaMetadata = self.mediaMetadata {
completion(mediaMetadata)
return
}
guard let asset = self.fetchAsset() else {
completion(nil)
return
}
asset.mediaMetadata(completion: completion)
}
}
#endif
| mit | f24a9f47452c9f8c4053e5589ab56fb2 | 31.710145 | 229 | 0.653079 | 4.864224 | false | false | false | false |
saoudrizwan/Disk | Sources/Disk+Codable.swift | 1 | 8521 | // The MIT License (MIT)
//
// Copyright (c) 2017 Saoud Rizwan <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public extension Disk {
/// Save encodable struct to disk as JSON data
///
/// - Parameters:
/// - value: the Encodable struct to store
/// - directory: user directory to store the file in
/// - path: file location to store the data (i.e. "Folder/file.json")
/// - encoder: custom JSONEncoder to encode value
/// - Throws: Error if there were any issues encoding the struct or writing it to disk
static func save<T: Encodable>(_ value: T, to directory: Directory, as path: String, encoder: JSONEncoder = JSONEncoder()) throws {
if path.hasSuffix("/") {
throw createInvalidFileNameForStructsError()
}
do {
let url = try createURL(for: path, in: directory)
let data = try encoder.encode(value)
try createSubfoldersBeforeCreatingFile(at: url)
try data.write(to: url, options: .atomic)
} catch {
throw error
}
}
/// Append Codable struct JSON data to a file's data
///
/// - Parameters:
/// - value: the struct to store to disk
/// - path: file location to store the data (i.e. "Folder/file.json")
/// - directory: user directory to store the file in
/// - decoder: custom JSONDecoder to decode existing values
/// - encoder: custom JSONEncoder to encode new value
/// - Throws: Error if there were any issues with encoding/decoding or writing the encoded struct to disk
static func append<T: Codable>(_ value: T, to path: String, in directory: Directory, decoder: JSONDecoder = JSONDecoder(), encoder: JSONEncoder = JSONEncoder()) throws {
if path.hasSuffix("/") {
throw createInvalidFileNameForStructsError()
}
do {
if let url = try? getExistingFileURL(for: path, in: directory) {
let oldData = try Data(contentsOf: url)
if !(oldData.count > 0) {
try save([value], to: directory, as: path, encoder: encoder)
} else {
let new: [T]
if let old = try? decoder.decode(T.self, from: oldData) {
new = [old, value]
} else if var old = try? decoder.decode([T].self, from: oldData) {
old.append(value)
new = old
} else {
throw createDeserializationErrorForAppendingStructToInvalidType(url: url, type: value)
}
let newData = try encoder.encode(new)
try newData.write(to: url, options: .atomic)
}
} else {
try save([value], to: directory, as: path, encoder: encoder)
}
} catch {
throw error
}
}
/// Append Codable struct array JSON data to a file's data
///
/// - Parameters:
/// - value: the Codable struct array to store
/// - path: file location to store the data (i.e. "Folder/file.json")
/// - directory: user directory to store the file in
/// - decoder: custom JSONDecoder to decode existing values
/// - encoder: custom JSONEncoder to encode new value
/// - Throws: Error if there were any issues writing the encoded struct array to disk
static func append<T: Codable>(_ value: [T], to path: String, in directory: Directory, decoder: JSONDecoder = JSONDecoder(), encoder: JSONEncoder = JSONEncoder()) throws {
if path.hasSuffix("/") {
throw createInvalidFileNameForStructsError()
}
do {
if let url = try? getExistingFileURL(for: path, in: directory) {
let oldData = try Data(contentsOf: url)
if !(oldData.count > 0) {
try save(value, to: directory, as: path, encoder: encoder)
} else {
let new: [T]
if let old = try? decoder.decode(T.self, from: oldData) {
new = [old] + value
} else if var old = try? decoder.decode([T].self, from: oldData) {
old.append(contentsOf: value)
new = old
} else {
throw createDeserializationErrorForAppendingStructToInvalidType(url: url, type: value)
}
let newData = try encoder.encode(new)
try newData.write(to: url, options: .atomic)
}
} else {
try save(value, to: directory, as: path, encoder: encoder)
}
} catch {
throw error
}
}
/// Retrieve and decode a struct from a file on disk
///
/// - Parameters:
/// - path: path of the file holding desired data
/// - directory: user directory to retrieve the file from
/// - type: struct type (i.e. Message.self or [Message].self)
/// - decoder: custom JSONDecoder to decode existing values
/// - Returns: decoded structs of data
/// - Throws: Error if there were any issues retrieving the data or decoding it to the specified type
static func retrieve<T: Decodable>(_ path: String, from directory: Directory, as type: T.Type, decoder: JSONDecoder = JSONDecoder()) throws -> T {
if path.hasSuffix("/") {
throw createInvalidFileNameForStructsError()
}
do {
let url = try getExistingFileURL(for: path, in: directory)
let data = try Data(contentsOf: url)
let value = try decoder.decode(type, from: data)
return value
} catch {
throw error
}
}
}
extension Disk {
/// Helper method to create deserialization error for append(:path:directory:) functions
fileprivate static func createDeserializationErrorForAppendingStructToInvalidType<T>(url: URL, type: T) -> Error {
return Disk.createError(
.deserialization,
description: "Could not deserialize the existing data at \(url.path) to a valid type to append to.",
failureReason: "JSONDecoder could not decode type \(T.self) from the data existing at the file location.",
recoverySuggestion: "Ensure that you only append data structure(s) with the same type as the data existing at the file location.")
}
/// Helper method to create error for when trying to saving Codable structs as multiple files to a folder
fileprivate static func createInvalidFileNameForStructsError() -> Error {
return Disk.createError(
.invalidFileName,
description: "Cannot save/retrieve the Codable struct without a valid file name. Unlike how arrays of UIImages or Data are stored, Codable structs are not saved as multiple files in a folder, but rather as one JSON file. If you already successfully saved Codable struct(s) to your folder name, try retrieving it as a file named 'Folder' instead of as a folder 'Folder/'",
failureReason: "Disk does not save structs or arrays of structs as multiple files to a folder like it does UIImages or Data.",
recoverySuggestion: "Save your struct or array of structs as one file that encapsulates all the data (i.e. \"multiple-messages.json\")")
}
}
| mit | b5bd0a13e4ec987711603de9c622d44c | 49.420118 | 383 | 0.612487 | 4.723392 | false | false | false | false |
ahoppen/swift | test/Interpreter/convenience_init_peer_delegation.swift | 7 | 6558 | // RUN: %empty-directory(%t)
//
// RUN: %target-build-swift %s -Xfrontend -disable-objc-attr-requires-foundation-module -o %t/main
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %empty-directory(%t)
//
// RUN: sed -e 's/required//g' < %s > %t/without_required.swift
// RUN: %target-build-swift %t/without_required.swift -Xfrontend -disable-objc-attr-requires-foundation-module -o %t/without_required
// RUN: %target-codesign %t/without_required
// RUN: %target-run %t/without_required | %FileCheck %s
// RUN: %empty-directory(%t)
//
// RUN: %target-build-swift %s -Xfrontend -disable-objc-attr-requires-foundation-module -o %t/main -swift-version 5
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %empty-directory(%t)
//
// RUN: sed -e 's/required//g' < %s > %t/without_required.swift
// RUN: %target-build-swift %t/without_required.swift -Xfrontend -disable-objc-attr-requires-foundation-module -o %t/without_required -swift-version 5
// RUN: %target-codesign %t/without_required
// RUN: %target-run %t/without_required | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
// XFAIL: CPU=arm64e
// REQUIRES: rdar92102119
import Darwin
class Base {
init(swift: ()) {
print("\(#function) \(type(of: self))")
}
@objc(initAsObjC) required init(objc: ()) {
print("\(#function) \(type(of: self))")
}
convenience init(swiftToSwift: ()) {
print("\(#function) \(type(of: self))")
self.init(swift: ())
}
@objc convenience required init(objcToSwift: ()) {
print("\(#function) \(type(of: self))")
self.init(swift: ())
}
convenience init(swiftToObjC: ()) {
print("\(#function) \(type(of: self))")
self.init(objc: ())
}
@objc convenience required init(objcToObjC: ()) {
print("\(#function) \(type(of: self))")
self.init(objc: ())
}
convenience init(swiftToSwiftConvenience: ()) {
print("\(#function) \(type(of: self))")
self.init(swiftToSwift: ())
}
@objc convenience required init(objcToSwiftConvenience: ()) {
print("\(#function) \(type(of: self))")
self.init(swiftToSwift: ())
}
convenience init(swiftToObjCConvenience: ()) {
print("\(#function) \(type(of: self))")
self.init(objcToObjC: ())
}
@objc convenience required init(objcToObjCConvenience: ()) {
print("\(#function) \(type(of: self))")
self.init(objcToObjC: ())
}
}
class Sub: Base {}
@objc protocol ForceObjCDispatch {
@objc(initAsObjC) init(objc: ())
init(objcToSwift: ())
init(objcToObjC: ())
init(objcToSwiftConvenience: ())
init(objcToObjCConvenience: ())
}
// Replace swift_allocObject so that we can keep track of what gets allocated.
var baseCounter = 0
var subCounter = 0
typealias AllocObjectType =
@convention(c) (UnsafeRawPointer, Int, Int) -> UnsafeMutableRawPointer
let allocObjectImpl =
dlsym(UnsafeMutableRawPointer(bitPattern: -1), "_swift_allocObject")
.assumingMemoryBound(to: AllocObjectType.self)
/// Like `ObjectIdentifier.init(Any.Type)`, but with a pointer as the
/// destination type.
func asUnsafeRawPointer(_ someClass: AnyObject.Type) -> UnsafeRawPointer {
let opaque = Unmanaged.passUnretained(someClass as AnyObject).toOpaque()
return UnsafeRawPointer(opaque)
}
let originalAllocObject = allocObjectImpl.pointee
allocObjectImpl.pointee = {
switch $0 {
case asUnsafeRawPointer(Base.self):
baseCounter += 1
case asUnsafeRawPointer(Sub.self):
subCounter += 1
default:
break
}
return originalAllocObject($0, $1, $2)
}
/// Checks that `op` performs `base` allocations of Base and `sub` allocations
/// of Sub.
@inline(never)
func check(base: Int = 0, sub: Int = 0,
file: StaticString = #file, line: UInt = #line,
op: () -> AnyObject) {
baseCounter = 0
subCounter = 0
_ = op()
precondition(baseCounter == base,
"expected \(base) Base instances, got \(baseCounter)",
file: file, line: line)
precondition(subCounter == sub,
"expected \(sub) Sub instances, got \(subCounter)",
file: file, line: line)
}
// CHECK: START
print("START")
// Check that this whole setup works.
// CHECK-NEXT: init(swift:) Base
check(base: 1) { Base(swift: ()) }
// CHECK-NEXT: init(swift:) Sub
check(sub: 1) { Sub(swift: ()) }
// CHECK-NEXT: init(objc:) Base
check(base: 1) { Base(objc: ()) }
// CHECK-NEXT: init(objc:) Sub
check(sub: 1) { Sub(objc: ()) }
// CHECK-NEXT: init(swiftToSwift:) Sub
// CHECK-NEXT: init(swift:) Sub
check(sub: 1) { Sub(swiftToSwift: ()) }
// CHECK-NEXT: init(objcToSwift:) Sub
// CHECK-NEXT: init(swift:) Sub
check(sub: 2) { Sub(objcToSwift: ()) }
// CHECK-NEXT: init(swiftToObjC:) Sub
// CHECK-NEXT: init(objc:) Sub
check(sub: 1) { Sub(swiftToObjC: ()) }
// CHECK-NEXT: init(objcToObjC:) Sub
// CHECK-NEXT: init(objc:) Sub
check(sub: 1) { Sub(objcToObjC: ()) }
// CHECK-NEXT: init(swiftToSwiftConvenience:) Sub
// CHECK-NEXT: init(swiftToSwift:) Sub
// CHECK-NEXT: init(swift:) Sub
check(sub: 1) { Sub(swiftToSwiftConvenience: ()) }
// CHECK-NEXT: init(objcToSwiftConvenience:) Sub
// CHECK-NEXT: init(swiftToSwift:) Sub
// CHECK-NEXT: init(swift:) Sub
check(sub: 2) { Sub(objcToSwiftConvenience: ()) }
// CHECK-NEXT: init(swiftToObjCConvenience:) Sub
// CHECK-NEXT: init(objcToObjC:) Sub
// CHECK-NEXT: init(objc:) Sub
check(sub: 1) { Sub(swiftToObjCConvenience: ()) }
// CHECK-NEXT: init(objcToObjCConvenience:) Sub
// CHECK-NEXT: init(objcToObjC:) Sub
// CHECK-NEXT: init(objc:) Sub
check(sub: 1) { Sub(objcToObjCConvenience: ()) }
// Force ObjC dispatch without conforming Sub or Base to the protocol,
// because it's possible that `required` perturbs things and we want to test
// both ways.
let SubAsObjC = unsafeBitCast(Sub.self as AnyObject,
to: ForceObjCDispatch.Type.self)
// CHECK-NEXT: init(objc:) Sub
check(sub: 1) { SubAsObjC.init(objc: ()) }
// CHECK-NEXT: init(objcToSwift:) Sub
// CHECK-NEXT: init(swift:) Sub
check(sub: 2) { SubAsObjC.init(objcToSwift: ()) }
// CHECK-NEXT: init(objcToObjC:) Sub
// CHECK-NEXT: init(objc:) Sub
check(sub: 1) { SubAsObjC.init(objcToObjC: ()) }
// CHECK-NEXT: init(objcToSwiftConvenience:) Sub
// CHECK-NEXT: init(swiftToSwift:) Sub
// CHECK-NEXT: init(swift:) Sub
check(sub: 2) { SubAsObjC.init(objcToSwiftConvenience: ()) }
// CHECK-NEXT: init(objcToObjCConvenience:) Sub
// CHECK-NEXT: init(objcToObjC:) Sub
// CHECK-NEXT: init(objc:) Sub
check(sub: 1) { SubAsObjC.init(objcToObjCConvenience: ()) }
// CHECK-NEXT: END
print("END")
| apache-2.0 | 6278ef4558f4a89ae40419a46c45cca2 | 31.305419 | 150 | 0.665294 | 3.344212 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/GlobalBadgeNode.swift | 1 | 13652 | //
// GlobalBadgeNode.swift
// TelegramMac
//
// Created by keepcoder on 05/01/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import Postbox
import SwiftSignalKit
import TelegramCore
import InAppSettings
class GlobalBadgeNode: Node {
private let account:Account
private let sharedContext: SharedAccountContext
private let layoutChanged:(()->Void)?
private let excludePeerId:PeerId?
private let disposable:MetaDisposable = MetaDisposable()
private var textLayout:(TextNodeLayout, TextNode)?
var customLayout: Bool = false
var xInset:CGFloat = 0
var onUpdate:(()->Void)?
private var attributedString:NSAttributedString? {
didSet {
if let attributedString = attributedString {
textLayout = TextNode.layoutText(maybeNode: nil, attributedString, nil, 1, .middle, NSMakeSize(CGFloat.greatestFiniteMagnitude, CGFloat.greatestFiniteMagnitude), nil, false, .left)
size = NSMakeSize(textLayout!.0.size.width + 8, textLayout!.0.size.height + 7)
size = NSMakeSize(max(size.height,size.width), size.height)
} else {
textLayout = nil
size = NSZeroSize
}
setNeedDisplay()
if let superview = view?.superview as? View, !self.customLayout {
superview.customHandler.layout = { [weak self] view in
if let strongSelf = self {
if strongSelf.layoutChanged == nil {
var origin:NSPoint = NSZeroPoint
let center = view.focus(strongSelf.size)
origin = NSMakePoint(floorToScreenPixels(System.backingScale, center.midX) + strongSelf.xInset, 4)
origin.x = min(view.frame.width - strongSelf.size.width - 4, origin.x)
strongSelf.frame = NSMakeRect(origin.x,origin.y,strongSelf.size.width,strongSelf.size.height)
} else {
strongSelf.view?.setFrameSize(strongSelf.size)
strongSelf.layoutChanged?()
}
}
}
}
view?.superview?.needsLayout = true
onUpdate?()
}
}
override func update() {
let attributedString = self.attributedString
self.attributedString = attributedString
}
override func setNeedDisplay() {
super.setNeedDisplay()
}
var isSelected: Bool = false {
didSet {
if oldValue != self.isSelected {
self.view?.needsDisplay = true
let copy = self.attributedString?.mutableCopy() as? NSMutableAttributedString
guard let attr = copy else {
return
}
attr.addAttribute(.foregroundColor, value: getColor(!isSelected), range: attr.range)
self.attributedString = copy
}
}
}
private let getColor: (Bool) -> NSColor
init(_ account: Account, sharedContext: SharedAccountContext, dockTile: Bool = false, collectAllAccounts: Bool = false, excludePeerId:PeerId? = nil, excludeGroupId: PeerGroupId? = nil, view: View? = nil, layoutChanged:(()->Void)? = nil, getColor: @escaping(Bool) -> NSColor = { _ in return theme.colors.redUI }, fontSize: CGFloat = .small, applyFilter: Bool = true, filter: ChatListFilter? = nil, removeWhenSidebar: Bool = false, sync: Bool = false) {
self.account = account
self.excludePeerId = excludePeerId
self.layoutChanged = layoutChanged
self.sharedContext = sharedContext
self.getColor = getColor
super.init(view)
struct Result : Equatable {
let dockText: String?
let total:Int32
init(dockText: String?, total: Int32) {
self.dockText = dockText
self.total = max(total, 0)
}
}
var items:[UnreadMessageCountsItem] = []
let peerSignal: Signal<(Peer, Bool)?, NoError>
if let peerId = excludePeerId {
items.append(.peer(id: peerId, handleThreads: true))
let notificationKeyView: PostboxViewKey = .peerNotificationSettings(peerIds: Set([peerId]))
peerSignal = combineLatest(account.postbox.loadedPeerWithId(peerId), account.postbox.combinedView(keys: [notificationKeyView]) |> map { view in
return ((view.views[notificationKeyView] as? PeerNotificationSettingsView)?.notificationSettings[peerId])?.isRemovedFromTotalUnreadCount(default: false) ?? false
}) |> map {Optional($0)}
} else {
peerSignal = .single(nil)
}
let signal: Signal<[(Int32, RenderedTotalUnreadCountType)], NoError>
if collectAllAccounts {
signal = sharedContext.activeAccountsWithInfo |> mapToSignal { primaryId, accounts in
return combineLatest(accounts.filter { $0.account.id != account.id }.map { renderedTotalUnreadCount(accountManager: sharedContext.accountManager, postbox: $0.account.postbox) })
}
} else {
signal = renderedTotalUnreadCount(accountManager: sharedContext.accountManager, postbox: account.postbox) |> map { [$0] }
}
var unreadCountItems: [UnreadMessageCountsItem] = []
unreadCountItems.append(.total(nil))
let keys: [PostboxViewKey] = []
var s:Signal<Result, NoError>
if let filter = filter {
s = chatListFilterItems(engine: TelegramEngine(account: account), accountManager: sharedContext.accountManager) |> map { value in
if let unread = value.count(for: filter) {
return Result(dockText: nil, total: Int32(unread.count))
} else {
return Result(dockText: nil, total: 0)
}
} |> deliverOnMainQueue
} else {
s = combineLatest(signal, account.postbox.unreadMessageCountsView(items: items), account.postbox.combinedView(keys: keys), appNotificationSettings(accountManager: sharedContext.accountManager), peerSignal) |> map { (counts, view, keysView, inAppSettings, peerSettings) in
if !applyFilter || filter == nil {
var excludeTotal: Int32 = 0
var dockText: String?
let totalValue = !inAppSettings.badgeEnabled ? 0 : (collectAllAccounts && !inAppSettings.notifyAllAccounts ? 0 : max(0, counts.reduce(0, { $0 + $1.0 })))
if totalValue > 0 {
dockText = "\(max(0, totalValue))"
}
excludeTotal = totalValue
if items.count == 1, let peerSettings = peerSettings {
if let count = view.count(for: items[0]), count > 0 {
var removable = false
switch inAppSettings.totalUnreadCountDisplayStyle {
case .raw:
removable = true
case .filtered:
if !peerSettings.1 {
removable = true
}
}
if removable {
switch inAppSettings.totalUnreadCountDisplayCategory {
case .chats:
excludeTotal -= 1
case .messages:
excludeTotal -= count
}
}
}
}
return Result(dockText: dockText, total: excludeTotal)
}
return Result(dockText: nil, total: 0)
} |> deliverOnMainQueue
}
s = combineLatest(s, chatListFolderSettings(account.postbox)) |> map {
return Result(dockText: $0.dockText, total: $1.sidebar && removeWhenSidebar ? 0 : $0.total)
} |> deliverOnMainQueue
let semaphore = DispatchSemaphore(value: 0)
self.disposable.set(s.start(next: { [weak self] result in
if let strongSelf = self {
if result.total == 0 {
strongSelf.attributedString = nil
} else {
strongSelf.attributedString = .initialize(string: Int(result.total).prettyNumber, color: getColor(strongSelf.isSelected) != theme.colors.redUI ? theme.colors.underSelectedColor : .white, font: .bold(fontSize))
}
strongSelf.layoutChanged?()
if dockTile {
NSApplication.shared.dockTile.badgeLabel = result.dockText
forceUpdateStatusBarIconByDockTile(sharedContext: sharedContext)
}
}
if sync {
semaphore.signal()
}
}))
if sync {
semaphore.wait()
}
}
override public func draw(_ layer: CALayer, in ctx: CGContext) {
if let view = view {
ctx.setFillColor(getColor(isSelected).cgColor)
ctx.round(self.size, self.size.height/2.0)
ctx.fill(layer.bounds)
if let textLayout = textLayout {
let focus = view.focus(textLayout.0.size)
textLayout.1.draw(focus, in: ctx, backingScaleFactor: view.backingScaleFactor, backgroundColor: view.backgroundColor)
}
}
}
deinit {
disposable.dispose()
}
}
func forceUpdateStatusBarIconByDockTile(sharedContext: SharedAccountContext) {
if let count = Int(NSApplication.shared.dockTile.badgeLabel ?? "0") {
var color: NSColor = .black
if #available(OSX 10.14, *) {
if systemAppearance.name != .aqua {
color = .white
}
}
if #available(OSX 11.0, *) {
color = .white
}
resourcesQueue.async {
let icon = generateStatusBarIcon(count, color: color)
Queue.mainQueue().async {
sharedContext.updateStatusBarImage(icon)
}
}
}
}
private func generateStatusBarIcon(_ unreadCount: Int, color: NSColor) -> NSImage {
let icon = NSImage(named: "StatusIcon")!
// if unreadCount > 0 {
// return NSImage(cgImage: icon.precomposed(whitePalette.redUI), size: icon.size)
// } else {
// return icon
// }
var string = "\(unreadCount)"
if string.count > 3 {
string = ".." + string.nsstring.substring(from: string.length - 2)
}
let attributedString = NSAttributedString.initialize(string: string, color: .white, font: .medium(8), coreText: true)
let textLayout = TextNode.layoutText(maybeNode: nil, attributedString, nil, 1, .start, NSMakeSize(18, CGFloat.greatestFiniteMagnitude), nil, false, .center)
let generated: CGImage?
if unreadCount > 0 {
generated = generateImage(NSMakeSize(max((textLayout.0.size.width + 4), (textLayout.0.size.height + 4)), (textLayout.0.size.height + 2)), scale: nil, rotatedContext: { size, ctx in
let rect = NSMakeRect(0, 0, size.width, size.height)
ctx.clear(rect)
ctx.setFillColor(NSColor.red.cgColor)
ctx.round(size, size.height/2.0)
ctx.fill(rect)
ctx.setBlendMode(.clear)
let focus = NSMakePoint((rect.width - textLayout.0.size.width) / 2, (rect.height - textLayout.0.size.height) / 2)
textLayout.1.draw(NSMakeRect(focus.x, 2, textLayout.0.size.width, textLayout.0.size.height), in: ctx, backingScaleFactor: 2.0, backgroundColor: .white)
})!
} else {
generated = nil
}
let full = generateImage(NSMakeSize(24, 20), contextGenerator: { size, ctx in
let rect = NSMakeRect(0, 0, size.width, size.height)
ctx.clear(rect)
ctx.draw(icon.precomposed(color), in: NSMakeRect((size.width - icon.size.width) / 2, 2, icon.size.width, icon.size.height))
if let generated = generated {
ctx.setBlendMode(.clear)
let cgPath = CGMutablePath()
let clearSize = NSMakeSize(generated.size.width + 1, generated.size.height + 1)
cgPath.addRoundedRect(in: NSMakeRect(rect.width - clearSize.width / System.backingScale, 0, clearSize.width / System.backingScale, clearSize.height / System.backingScale), cornerWidth: clearSize.height / System.backingScale / 2, cornerHeight: clearSize.height / System.backingScale / 2)
ctx.addPath(cgPath)
ctx.fillPath()
ctx.setBlendMode(.normal)
ctx.draw(generated, in: NSMakeRect(rect.width - generated.size.width / System.backingScale, 0, generated.size.width / System.backingScale, generated.size.height / System.backingScale))
}
})!
let image = NSImage(cgImage: full, size: full.backingSize)
image.isTemplate = true
return image
}
| gpl-2.0 | badb78ac88c51235610981acaf1bd8b0 | 41.927673 | 455 | 0.557761 | 5.005867 | false | false | false | false |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/DoubleLabel.swift | 1 | 3263 | //
// DoubleLabel.swift
// wanlezu
//
// Created by 伯驹 黄 on 2017/6/18.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import UIKit
extension UIFont {
static var systemFont: UIFont {
return UIFont.systemFont(ofSize: UIFont.systemFontSize)
}
}
class DoubleLabel: UIView {
private let topLabel = UILabel()
private let bottomLabel = UILabel()
/// Default 1
var topNumberOfLines = 1 {
didSet {
topLabel.numberOfLines = topNumberOfLines
}
}
/// Default 1
var bottomNumberOfLines = 1 {
didSet {
bottomLabel.numberOfLines = bottomNumberOfLines
}
}
/// Default 14 systemFont
var topFont = UIFont.systemFont {
didSet {
topLabel.font = topFont
}
}
/// Default 14 systemFont
var bottomFont = UIFont.systemFont {
didSet {
bottomLabel.font = bottomFont
}
}
/// Default UIColor.darkText
var topTextColor = UIColor.darkText {
didSet {
topLabel.textColor = topTextColor
}
}
/// Default UIColor.darkText
var bottomTextColor = UIColor.darkText {
didSet {
bottomLabel.textColor = bottomTextColor
}
}
/// Default 10
var lineSpacing: CGFloat = 10 {
didSet {
setNeedsLayout()
}
}
var textAlignment: NSTextAlignment = .center {
didSet {
topLabel.textAlignment = textAlignment
bottomLabel.textAlignment = textAlignment
}
}
var topAttributText: NSAttributedString? {
didSet {
topLabel.attributedText = topAttributText
}
}
var bottomAttributText: NSAttributedString? {
didSet {
bottomLabel.attributedText = bottomAttributText
}
}
var topText: String? {
didSet {
topLabel.text = topText
}
}
var bottomText: String? {
didSet {
bottomLabel.text = bottomText
}
}
convenience init(alignment: NSTextAlignment = .center) {
self.init(frame: .zero, alignment: alignment)
}
init(frame: CGRect, alignment: NSTextAlignment = .center) {
super.init(frame: frame)
textAlignment = alignment
bottomLabel.font = bottomFont
topLabel.font = topFont
topLabel.textAlignment = alignment
bottomLabel.textAlignment = alignment
addSubview(topLabel)
addSubview(bottomLabel)
}
override func layoutSubviews() {
super.layoutSubviews()
topLabel.snp.makeConstraints { (make) in
make.leading.trailing.equalToSuperview()
make.top.equalToSuperview()
}
bottomLabel.snp.makeConstraints { (make) in
make.leading.trailing.equalTo(topLabel)
make.top.equalTo(topLabel.snp.bottom).offset(lineSpacing)
make.bottom.equalToSuperview()
}
}
func setContent(_ content: (String, String)) {
topText = content.0
bottomText = content.1
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | cd63660d3031e0fdb8741312a87ddb9c | 21.555556 | 69 | 0.580973 | 5.027864 | false | false | false | false |
koscida/Kos_AMAD_Spring2015 | Fall_16/Life/Life/Level.swift | 1 | 551 | //
// Level.swift
// Life
//
// Created by Brittany Ann Kos on 12/4/16.
// Copyright © 2016 Kode Studios. All rights reserved.
//
import Foundation
import UIKit
import SpriteKit
class Level {
// MARK: Properties
var name: String = ""
var moneyMax: CGFloat = 0
var moneyAddValue: CGFloat = 0
var items = [Item]()
// MARK: Initialization
init(name: String, moneyMax: CGFloat, moneyAddValue: CGFloat, items: [Item]) {
self.name = name
self.moneyMax = moneyMax
self.moneyAddValue = moneyAddValue
self.items = items
}
} | gpl-3.0 | e42100fac08d20eff2caad5149ba4f30 | 15.205882 | 79 | 0.674545 | 3.293413 | false | false | false | false |
GiorgioNatili/CryptoMessages | CryptoMessagesTests/AuthenticationViewControllerTest.swift | 1 | 5052 | //
// AuthenticationViewControllerTest.swift
// CryptoMessages
//
// Created by Giorgio Natili on 5/7/17.
// Copyright © 2017 Giorgio Natili. All rights reserved.
//
import UIKit
import Quick
import Nimble
@testable import CryptoMessages
class AuthenticationViewControllerTest: QuickSpec {
override func spec() {
var viewController: AuthenticationViewController!
beforeEach {
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
viewController = storyboard.instantiateInitialViewController() as! AuthenticationViewController
UIApplication.shared.keyWindow!.rootViewController = viewController
}
describe(".viewDidLoad()") {
beforeEach {
// Access the view to trigger BananaViewController.viewDidLoad().
let _ = viewController.view
}
it("It should contains labels, text inputs, etc.") {
// Since the controls are only initialized when the view is loaded, this
// would fail if we didn't access the view in the `beforeEach` above.
expect(viewController.username).notTo(beNil())
expect(viewController.usernameLabel).notTo(beNil())
expect(viewController.password).notTo(beNil())
expect(viewController.passwordLabel).notTo(beNil())
expect(viewController.errorMessage).notTo(beNil())
expect(viewController.login).notTo(beNil())
}
}
describe("dynamic text rendering", {
beforeEach {
// Triggers .viewDidLoad(), .viewWillAppear(), and .viewDidAppear() events.
viewController.beginAppearanceTransition(true, animated: false)
viewController.endAppearanceTransition()
}
it("It should load resources from a locale file") {
expect(viewController.usernameLabel.text).toEventuallyNot(contain("Label"))
expect(viewController.passwordLabel.text).toEventuallyNot(contain("Label"))
expect(viewController.errorMessage.text).toEventuallyNot(contain("Label"))
}
})
describe("Input field validation") {
beforeEach {
// Access the view to trigger AuthenticationViewController.viewDidLoad().
let _ = viewController.view
}
it("It should render an error message when username and password are missing"){
viewController.login.sendActions(for: UIControlEvents.touchUpInside)
expect(viewController.errorMessage.text?.characters.count).toEventually(beGreaterThan(0), timeout: 1)
}
it("It should render an error message the password is missing"){
viewController.username.text = "Hannibal"
viewController.login.sendActions(for: UIControlEvents.touchUpInside)
expect(viewController.errorMessage.text?.characters.count).toEventually(beGreaterThan(0), timeout: 1)
}
it("It should render an error message the username is missing"){
viewController.password.text = "The cannibal"
viewController.login.sendActions(for: UIControlEvents.touchUpInside)
expect(viewController.errorMessage.text?.characters.count).toEventually(beGreaterThan(0), timeout: 1)
}
it("It should render an error message if the username and password fiels are filled but username is not an email"){
viewController.username.text = "Hannibal"
viewController.password.text = "thecannibal"
viewController.login.sendActions(for: UIControlEvents.touchUpInside)
expect(viewController.errorMessage.text?.characters.count).toEventually(beGreaterThan(0))
}
it("It should not render any error message if the username and password fiels are correctly filled"){
viewController.username.text = "[email protected]"
viewController.password.text = "thecannibal"
viewController.login.sendActions(for: UIControlEvents.touchUpInside)
expect(viewController.errorMessage.text).toEventually(beEmpty(), timeout: 1)
}
}
describe("Input field validation") {
beforeEach {
// Access the view to trigger AuthenticationViewController.viewDidLoad().
let _ = viewController.view
}
}
}
}
| unlicense | 5b2cd16f47a0d77dbf64e83d2a0e2a2a | 40.401639 | 127 | 0.574144 | 6.220443 | false | false | false | false |
austinzheng/swift | test/Constraints/diagnostics.swift | 2 | 55940 | // RUN: %target-typecheck-verify-swift
protocol P {
associatedtype SomeType
}
protocol P2 {
func wonka()
}
extension Int : P {
typealias SomeType = Int
}
extension Double : P {
typealias SomeType = Double
}
func f0(_ x: Int,
_ y: Float) { }
func f1(_: @escaping (Int, Float) -> Int) { }
func f2(_: (_: (Int) -> Int)) -> Int {}
func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {}
func f4(_ x: Int) -> Int { }
func f5<T : P2>(_ : T) { }
func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {}
var i : Int
var d : Double
// Check the various forms of diagnostics the type checker can emit.
// Tuple size mismatch.
f1(
f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}}
)
// Tuple element unused.
f0(i, i,
i) // expected-error{{extra argument in call}}
// Position mismatch
f5(f4) // expected-error {{argument type '(Int) -> Int' does not conform to expected type 'P2'}}
// Tuple element not convertible.
f0(i,
d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}}
)
// Function result not a subtype.
f1(
f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}}
)
f3(
f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}}
)
f4(i, d) // expected-error {{extra argument in call}}
// Missing member.
i.wobble() // expected-error{{value of type 'Int' has no member 'wobble'}}
// Generic member does not conform.
extension Int {
func wibble<T: P2>(_ x: T, _ y: T) -> T { return x }
func wubble<T>(_ x: (Int) -> T) -> T { return x(self) }
}
i.wibble(3, 4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Generic member args correct, but return type doesn't match.
struct A : P2 {
func wonka() {}
}
let a = A()
for j in i.wibble(a, a) { // expected-error {{type 'A' does not conform to protocol 'Sequence'}}
}
// Generic as part of function/tuple types
func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) { // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{20-26=()}}
return (c: 0, i: g(()))
}
func f7() -> (c: Int, v: A) {
let g: (Void) -> A = { _ in return A() } // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{10-16=()}}
return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}}
}
func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {}
f8(3, f4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
typealias Tup = (Int, Double)
func f9(_ x: Tup) -> Tup { return x }
f8((1,2.0), f9) // expected-error {{argument type 'Tup' (aka '(Int, Double)') does not conform to expected type 'P2'}}
// <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals
1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}}
[1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}}
"awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}}
// Does not conform to protocol.
f5(i) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Make sure we don't leave open existentials when diagnosing.
// <rdar://problem/20598568>
func pancakes(_ p: P2) {
f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}}
f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}}
}
protocol Shoes {
static func select(_ subject: Shoes) -> Self
}
// Here the opaque value has type (metatype_type (archetype_type ... ))
func f(_ x: Shoes, asType t: Shoes.Type) {
return t.select(x) // expected-error{{unexpected non-void return value in void function}}
}
precedencegroup Starry {
associativity: left
higherThan: MultiplicationPrecedence
}
infix operator **** : Starry
func ****(_: Int, _: String) { }
i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
infix operator ***~ : Starry
func ***~(_: Int, _: String) { }
i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
@available(*, unavailable, message: "call the 'map()' method on the sequence")
public func myMap<C : Collection, T>( // expected-note {{'myMap' has been explicitly marked unavailable here}}
_ source: C, _ transform: (C.Iterator.Element) -> T
) -> [T] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "call the 'map()' method on the optional value")
public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? {
fatalError("unavailable function can't be called")
}
// <rdar://problem/20142523>
func rdar20142523() {
myMap(0..<10, { x in // expected-error{{'myMap' is unavailable: call the 'map()' method on the sequence}}
()
return x
})
}
// <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral
func rdar21080030() {
var s = "Hello"
// SR-7599: This should be `cannot_call_non_function_value`
if s.count() == 0 {} // expected-error{{cannot invoke 'count' with no arguments}}
}
// <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments
func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136()'}}
r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors
func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}}
// <rdar://problem/17080659> Error Message QOI - wrong return type in an overload
func recArea(_ h: Int, w : Int) {
return h * w // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong
func r17224804(_ monthNumber : Int) {
// expected-error @+2 {{binary operator '+' cannot be applied to operands of type 'String' and 'Int'}}
// expected-note @+1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber)
}
// <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?'
func r17020197(_ x : Int?, y : Int) {
if x! { } // expected-error {{'Int' is not convertible to 'Bool'}}
// <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible
if y {} // expected-error {{'Int' is not convertible to 'Bool'}}
}
// <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different
func validateSaveButton(_ text: String) {
return (text.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype
class r20201968C {
func blah() {
r20201968C.blah() // expected-error {{instance member 'blah' cannot be used on type 'r20201968C'; did you mean to use a value of this type instead?}}
}
}
// <rdar://problem/21459429> QoI: Poor compilation error calling assert
func r21459429(_ a : Int) {
assert(a != nil, "ASSERT COMPILATION ERROR")
// expected-warning @-1 {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
}
// <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an index of type 'Int'
struct StructWithOptionalArray {
var array: [Int]?
}
func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int {
return foo.array[0] // expected-error {{value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'}}
// expected-note@-1{{chain the optional using '?' to access member 'subscript' only for non-'nil' base values}}{{19-19=?}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{19-19=!}}
}
// <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types
var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}}
// <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf
String().asdf // expected-error {{value of type 'String' has no member 'asdf'}}
// <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment
protocol r21553065Protocol {}
class r21553065Class<T : AnyObject> {} // expected-note{{requirement specified as 'T' : 'AnyObject'}}
_ = r21553065Class<r21553065Protocol>() // expected-error {{'r21553065Class' requires that 'r21553065Protocol' be a class type}}
// Type variables not getting erased with nested closures
struct Toe {
let toenail: Nail // expected-error {{use of undeclared type 'Nail'}}
func clip() {
toenail.inspect { x in
toenail.inspect { y in }
}
}
}
// <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic
class r21447318 {
var x = 42
func doThing() -> r21447318 { return self }
}
func test21447318(_ a : r21447318, b : () -> r21447318) {
a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}}
b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}}
}
// <rdar://problem/20409366> Diagnostics for init calls should print the class name
class r20409366C {
init(a : Int) {}
init?(a : r20409366C) {
let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}}
}
}
// <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match
func r18800223(_ i : Int) {
// 20099385
_ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}}
// 19648528
_ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}}
var buttonTextColor: String?
_ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{type of expression is ambiguous without more context}}
}
// <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back
_ = { $0 } // expected-error {{unable to infer closure type in the current context}}
_ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}}
_ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}}
// <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure.
func rdar21784170() {
let initial = (1.0 as Double, 2.0 as Double)
(Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}}
}
// <rdar://problem/21829141> BOGUS: unexpected trailing closure
func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } }
func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } }
let expectType1 = expect(Optional(3))(Optional<Int>.self)
let expectType1Check: Int = expectType1
// <rdar://problem/19804707> Swift Enum Scoping Oddity
func rdar19804707() {
enum Op {
case BinaryOperator((Double, Double) -> Double)
}
var knownOps : Op
knownOps = Op.BinaryOperator({$1 - $0})
knownOps = Op.BinaryOperator(){$1 - $0}
knownOps = Op.BinaryOperator{$1 - $0}
knownOps = .BinaryOperator({$1 - $0})
// rdar://19804707 - trailing closures for contextual member references.
knownOps = .BinaryOperator(){$1 - $0}
knownOps = .BinaryOperator{$1 - $0}
_ = knownOps
}
func f7(_ a: Int) -> (_ b: Int) -> Int {
return { b in a+b }
}
_ = f7(1)(1)
f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(b: 1.0) // expected-error{{extraneous argument label 'b:' in call}}
let f8 = f7(2)
_ = f8(1)
f8(10) // expected-warning {{result of call to function returning 'Int' is unused}}
f8(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f8(b: 1.0) // expected-error {{extraneous argument label 'b:' in call}}
class CurriedClass {
func method1() {}
func method2(_ a: Int) -> (_ b : Int) -> () { return { b in () } }
func method3(_ a: Int, b : Int) {} // expected-note 5 {{'method3(_:b:)' declared here}}
}
let c = CurriedClass()
_ = c.method1
c.method1(1) // expected-error {{argument passed to call that takes no arguments}}
_ = c.method2(1)
_ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1)(2)
c.method2(1)(c: 2) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(c: 2.0) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method1(c)()
_ = CurriedClass.method1(c)
CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}}
CurriedClass.method1(2.0)(1) // expected-error {{instance member 'method1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(32)(b: 1) // expected-error{{extraneous argument label 'b:' in call}}
_ = CurriedClass.method2(c)
_ = CurriedClass.method2(c)(32)
_ = CurriedClass.method2(1,2) // expected-error {{instance member 'method2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{extraneous argument label 'c:'}}
CurriedClass.method3(c)(32, b: 1)
_ = CurriedClass.method3(c)
_ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }}
_ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}}
_ = CurriedClass.method3(1, 2) // expected-error {{instance member 'method3' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}}
CurriedClass.method3(c)(c: 1.0) // expected-error {{missing argument for parameter #1 in call}}
extension CurriedClass {
func f() {
method3(1, b: 2)
method3() // expected-error {{missing argument for parameter #1 in call}}
method3(42) // expected-error {{missing argument for parameter 'b' in call}}
method3(self) // expected-error {{missing argument for parameter 'b' in call}}
}
}
extension CurriedClass {
func m1(_ a : Int, b : Int) {}
func m2(_ a : Int) {}
}
// <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method
CurriedClass.m1(2, b: 42) // expected-error {{instance member 'm1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method
CurriedClass.m2(12) // expected-error {{instance member 'm2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/20491794> Error message does not tell me what the problem is
enum Color {
case Red
case Unknown(description: String)
static func rainbow() -> Color {}
static func overload(a : Int) -> Color {}
static func overload(b : Int) -> Color {}
static func frob(_ a : Int, b : inout Int) -> Color {}
static var svar: Color { return .Red }
}
// FIXME: This used to be better: "'map' produces '[T]', not the expected contextual result type '(Int, Color)'"
let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error {{expression type '((Int) throws -> _) throws -> [_]' is ambiguous without more context}}
let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}}
let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }}
let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }}
let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }}
let _: Color = .Unknown // expected-error {{member 'Unknown' expects argument of type '(description: String)'}}
let _: Color = .Unknown(42) // expected-error {{missing argument label 'description:' in call}}
let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}}
let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}}
let _ : Color = .rainbow // expected-error {{member 'rainbow' is a function; did you mean to call it?}} {{25-25=()}}
let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .overload(1.0) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .overload(1) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .frob(1.0, &i) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1.0, b: &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1, i) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{28-28=&}}
let _: Color = .frob(1, &d) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
someColor = .svar() // expected-error {{static property 'svar' is not a function}}
someColor = .svar(1) // expected-error {{static property 'svar' is not a function}}
func testTypeSugar(_ a : Int) {
typealias Stride = Int
let x = Stride(a)
x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
}
// <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr
func r21974772(_ y : Int) {
let x = &(1.0 + y) // expected-error {{use of extraneous '&'}}
}
// <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc
protocol r22020088P {}
func r22020088Foo<T>(_ t: T) {}
func r22020088bar(_ p: r22020088P?) {
r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}}
}
// <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type
func f(_ arguments: [String]) -> [ArraySlice<String>] {
return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" })
}
struct AOpts : OptionSet {
let rawValue : Int
}
class B {
func function(_ x : Int8, a : AOpts) {}
func f2(_ a : AOpts) {}
static func f1(_ a : AOpts) {}
}
class GenClass<T> {}
struct GenStruct<T> {}
enum GenEnum<T> {}
func test(_ a : B) {
B.f1(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
a.function(42, a: nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
a.function(42, nil) // expected-error {{missing argument label 'a:' in call}}
a.f2(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
func foo1(_ arg: Bool) -> Int {return nil}
func foo2<T>(_ arg: T) -> GenClass<T> {return nil}
func foo3<T>(_ arg: T) -> GenStruct<T> {return nil}
func foo4<T>(_ arg: T) -> GenEnum<T> {return nil}
// expected-error@-4 {{'nil' is incompatible with return type 'Int'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenClass<T>'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenStruct<T>'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenEnum<T>'}}
let clsr1: () -> Int = {return nil}
let clsr2: () -> GenClass<Bool> = {return nil}
let clsr3: () -> GenStruct<String> = {return nil}
let clsr4: () -> GenEnum<Double?> = {return nil}
// expected-error@-4 {{'nil' is not compatible with closure result type 'Int'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenClass<Bool>'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenStruct<String>'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenEnum<Double?>'}}
var number = 0
var genClassBool = GenClass<Bool>()
var funcFoo1 = foo1
number = nil
genClassBool = nil
funcFoo1 = nil
// expected-error@-3 {{'nil' cannot be assigned to type 'Int'}}
// expected-error@-3 {{'nil' cannot be assigned to type 'GenClass<Bool>'}}
// expected-error@-3 {{'nil' cannot be assigned to type '(Bool) -> Int'}}
}
// <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure
typealias MyClosure = ([Int]) -> Bool
func r21684487() {
var closures = Array<MyClosure>()
let testClosure = {(list: [Int]) -> Bool in return true}
let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions;}}
}
// <rdar://problem/18397777> QoI: special case comparisons with nil
func r18397777(_ d : r21447318?) {
let c = r21447318()
if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to 'nil' always returns true}}
}
if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}}
}
if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{8-8= != nil)}}
}
if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{18-18= != nil)}}
}
}
// <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list
func r22255907_1<T>(_ a : T, b : Int) {}
func r22255907_2<T>(_ x : Int, a : T, b: Int) {}
func reachabilityForInternetConnection() {
var variable: Int = 42
r22255907_1(&variable, b: 2.1) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}}
r22255907_2(1, a: &variable, b: 2.1)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}}
}
// <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message
if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}}
_ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}}
// <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init
func r22263468(_ a : String?) {
typealias MyTuple = (Int, String)
_ = MyTuple(42, a) // expected-error {{value of optional type 'String?' must be unwrapped to a value of type 'String'}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
}
// rdar://22470302 - Crash with parenthesized call result.
class r22470302Class {
func f() {}
}
func r22470302(_ c: r22470302Class) {
print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}}
}
// <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile
extension String {
@available(*, unavailable, message: "calling this is unwise")
func unavail<T : Sequence> // expected-note 2 {{'unavail' has been explicitly marked unavailable here}}
(_ a : T) -> String where T.Iterator.Element == String {}
}
extension Array {
func g() -> String {
return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
func h() -> String {
return "foo".unavail([0]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
}
// <rdar://problem/22519983> QoI: Weird error when failing to infer archetype
func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {}
// expected-note @-1 {{in call to function 'safeAssign'}}
let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure
struct Radar21692808<Element> {
init(count: Int, value: Element) {}
}
func radar21692808() -> Radar21692808<Int> {
return Radar21692808<Int>(count: 1) { // expected-error {{cannot invoke initializer for type 'Radar21692808<Int>' with an argument list of type '(count: Int, () -> Int)'}}
// expected-note @-1 {{expected an argument list of type '(count: Int, value: Element)'}}
return 1
}
}
// <rdar://problem/17557899> - This shouldn't suggest calling with ().
func someOtherFunction() {}
func someFunction() -> () {
// Producing an error suggesting that this
return someOtherFunction // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic
func r23560128() {
var a : (Int,Int)?
a.0 = 42 // expected-error{{value of optional type '(Int, Int)?' must be unwrapped to refer to member '0' of wrapped base type '(Int, Int)'}}
// expected-note@-1{{chain the optional }}
// expected-note@-2{{force-unwrap using '!'}}
}
// <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping
struct ExampleStruct21890157 {
var property = "property"
}
var example21890157: ExampleStruct21890157?
example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' must be unwrapped to refer to member 'property' of wrapped base type 'ExampleStruct21890157'}}
// expected-note@-1{{chain the optional }}
// expected-note@-2{{force-unwrap using '!'}}
struct UnaryOp {}
_ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}}
// expected-note@-1 {{overloads for '-' exist with these partially matching parameter lists: (Double), (Float), (Float80)}}
// <rdar://problem/23433271> Swift compiler segfault in failure diagnosis
func f23433271(_ x : UnsafePointer<Int>) {}
func segfault23433271(_ a : UnsafeMutableRawPointer) {
f23433271(a[0]) // expected-error {{value of type 'UnsafeMutableRawPointer' has no subscripts}}
}
// <rdar://problem/23272739> Poor diagnostic due to contextual constraint
func r23272739(_ contentType: String) {
let actualAcceptableContentTypes: Set<String> = []
return actualAcceptableContentTypes.contains(contentType) // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets
func r23641896() {
var g = "Hello World"
g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<String.Index>'}}
_ = g[12] // expected-error {{'subscript(_:)' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}}
}
// <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note
func test17875634() {
var match: [(Int, Int)] = []
var row = 1
var col = 2
match.append(row, col) // expected-error {{instance method 'append' expects a single parameter of type '(Int, Int)'}} {{16-16=(}} {{24-24=)}}
}
// <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values
enum AssocTest {
case one(Int)
}
if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{binary operator '==' cannot be applied to two 'AssocTest' operands}}
// expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}}
// <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types
func r24251022() {
var a = 1
var b: UInt32 = 2
_ = a + b // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UInt32, UInt32)}}
a += a + // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+' exist with these partially matching parameter lists:}}
b
a += b // expected-error {{binary operator '+=' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+=' exist with these partially matching parameter lists: (inout Int, Int), (inout UInt32, UInt32)}}
}
func overloadSetResultType(_ a : Int, b : Int) -> Int {
// https://twitter.com/_jlfischer/status/712337382175952896
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
postfix operator +++
postfix func +++ <T>(_: inout T) -> T { fatalError() }
// <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect
func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) {
let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}}
_ = bytes[i+++] // expected-error {{cannot pass immutable value to mutating operator: 'i' is a 'let' constant}}
}
// SR-1594: Wrong error description when using === on non-class types
class SR1594 {
func sr1594(bytes : UnsafeMutablePointer<Int>, _ i : Int?) {
_ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}}
_ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}}
_ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}}
_ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}}
}
}
func nilComparison(i: Int, o: AnyObject) {
_ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}}
_ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}}
_ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
_ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
// FIXME(integers): uncomment these tests once the < is no longer ambiguous
// _ = i < nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil < i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i <= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil <= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i > nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil > i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i >= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil >= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
_ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}}
_ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}}
}
func secondArgumentNotLabeled(a: Int, _ b: Int) { }
secondArgumentNotLabeled(10, 20)
// expected-error@-1 {{missing argument label 'a:' in call}}
// <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion
func testImplConversion(a : Float?) -> Bool {}
func testImplConversion(a : Int?) -> Bool {
let someInt = 42
let a : Int = testImplConversion(someInt) // expected-error {{argument labels '(_:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'testImplConversion' exist with these partially matching parameter lists: (a: Float?), (a: Int?)}}
}
// <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands
class Foo23752537 {
var title: String?
var message: String?
}
extension Foo23752537 {
func isEquivalent(other: Foo23752537) {
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
// expected-error @+1 {{unexpected non-void return value in void function}}
return (self.title != other.title && self.message != other.message)
}
}
// <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
func rdar27391581(_ a : Int, b : Int) -> Int {
return a == b && b != 0
// expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints
func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {}
func read<T : BinaryInteger>() -> T? {
var buffer : T
let n = withUnsafeMutablePointer(to: &buffer) { (p) in
read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<_>' to expected argument type 'UnsafeMutableRawPointer'}}
}
}
func f23213302() {
var s = Set<Int>()
s.subtract(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}}
}
// <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context
func rdar24202058(a : Int) {
return a <= 480 // expected-error {{unexpected non-void return value in void function}}
}
// SR-1752: Warning about unused result with ternary operator
struct SR1752 {
func foo() {}
}
let sr1752: SR1752?
true ? nil : sr1752?.foo() // don't generate a warning about unused result since foo returns Void
// <rdar://problem/27891805> QoI: FailureDiagnosis doesn't look through 'try'
struct rdar27891805 {
init(contentsOf: String, encoding: String) throws {}
init(contentsOf: String, usedEncoding: inout String) throws {}
init<T>(_ t: T) {}
}
try rdar27891805(contentsOfURL: nil, usedEncoding: nil)
// expected-error@-1 {{argument labels '(contentsOfURL:, usedEncoding:)' do not match any available overloads}}
// expected-note@-2 {{overloads for 'rdar27891805' exist with these partially matching parameter lists: (contentsOf: String, encoding: String), (contentsOf: String, usedEncoding: inout String)}}
// Make sure RawRepresentable fix-its don't crash in the presence of type variables
class NSCache<K, V> {
func object(forKey: K) -> V? {}
}
class CacheValue {
func value(x: Int) -> Int {} // expected-note {{found this candidate}}
func value(y: String) -> String {} // expected-note {{found this candidate}}
}
func valueForKey<K>(_ key: K) -> CacheValue? {
let cache = NSCache<K, CacheValue>()
return cache.object(forKey: key)?.value // expected-error {{ambiguous reference to member 'value(x:)'}}
}
// SR-2242: poor diagnostic when argument label is omitted
func r27212391(x: Int, _ y: Int) {
let _: Int = x + y
}
func r27212391(a: Int, x: Int, _ y: Int) {
let _: Int = a + x + y
}
r27212391(3, 5) // expected-error {{missing argument label 'x:' in call}}
r27212391(3, y: 5) // expected-error {{incorrect argument labels in call (have '_:y:', expected 'x:_:')}}
r27212391(3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #1}} {{11-11=x: 5, }} {{12-18=}}
r27212391(y: 3, x: 5) // expected-error {{incorrect argument labels in call (have 'y:x:', expected 'x:_:')}} {{11-12=x}} {{17-20=}}
r27212391(y: 3, 5) // expected-error {{incorrect argument label in call (have 'y:_:', expected 'x:_:')}}
r27212391(x: 3, x: 5) // expected-error {{extraneous argument label 'x:' in call}}
r27212391(a: 1, 3, y: 5) // expected-error {{incorrect argument labels in call (have 'a:_:y:', expected 'a:x:_:')}}
r27212391(1, x: 3, y: 5) // expected-error {{incorrect argument labels in call (have '_:x:y:', expected 'a:x:_:')}}
r27212391(a: 1, y: 3, x: 5) // expected-error {{incorrect argument labels in call (have 'a:y:x:', expected 'a:x:_:')}} {{17-18=x}} {{23-26=}}
r27212391(a: 1, 3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #2}} {{17-17=x: 5, }} {{18-24=}}
// SR-1255
func foo1255_1() {
return true || false // expected-error {{unexpected non-void return value in void function}}
}
func foo1255_2() -> Int {
return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// Diagnostic message for initialization with binary operations as right side
let foo1255_3: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
let foo1255_4: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}}
let foo1255_5: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
let foo1255_6: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
// SR-2208
struct Foo2208 {
func bar(value: UInt) {}
}
func test2208() {
let foo = Foo2208()
let a: Int = 1
let b: Int = 2
let result = a / b
foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: UInt(result)) // Ok
}
// SR-2164: Erroneous diagnostic when unable to infer generic type
struct SR_2164<A, B> { // expected-note 3 {{'B' declared as parameter to type 'SR_2164'}} expected-note 2 {{'A' declared as parameter to type 'SR_2164'}} expected-note * {{generic type 'SR_2164' declared here}}
init(a: A) {}
init(b: B) {}
init(c: Int) {}
init(_ d: A) {}
init(e: A?) {}
}
struct SR_2164_Array<A, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Array'}} expected-note * {{generic type 'SR_2164_Array' declared here}}
init(_ a: [A]) {}
}
struct SR_2164_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Dict'}} expected-note * {{generic type 'SR_2164_Dict' declared here}}
init(a: [A: Double]) {}
}
SR_2164(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(c: 2) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164<Int>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
SR_2164<Int>(b: 1) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
let _ = SR_2164<Int, Bool>(a: 0) // Ok
let _ = SR_2164<Int, Bool>(b: true) // Ok
SR_2164<Int, Bool, Float>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
SR_2164<Int, Bool, Float>(b: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
// <rdar://problem/29850459> Swift compiler misreports type error in ternary expression
let r29850459_flag = true
let r29850459_a: Int = 0
let r29850459_b: Int = 1
func r29850459() -> Bool { return false }
let _ = (r29850459_flag ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = ({ true }() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = (r29850459() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = ((r29850459_flag || r29850459()) ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
// SR-6272: Tailored diagnostics with fixits for numerical conversions
func SR_6272_a() {
enum Foo: Int {
case bar
}
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{35-35=Int(}} {{43-43=)}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
let _: Int = Foo.bar.rawValue * Float(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{18-18=Float(}} {{34-34=)}}
// expected-note@+1 {{expected an argument list of type '(Float, Float)'}}
let _: Float = Foo.bar.rawValue * Float(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}}
Foo.bar.rawValue * Float(0)
}
func SR_6272_b() {
let lhs = Float(3)
let rhs = Int(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{24-24=Float(}} {{27-27=)}}
// expected-note@+1 {{expected an argument list of type '(Float, Float)'}}
let _: Float = lhs * rhs
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{16-16=Int(}} {{19-19=)}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
let _: Int = lhs * rhs
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{none}}
// expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}}
lhs * rhs
}
func SR_6272_c() {
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'String'}} {{none}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
Int(3) * "0"
struct S {}
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'S'}} {{none}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
Int(10) * S()
}
struct SR_6272_D: ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
init(integerLiteral: Int) {}
static func +(lhs: SR_6272_D, rhs: Int) -> Float { return 42.0 } // expected-note {{found this candidate}}
}
func SR_6272_d() {
let x: Float = 1.0
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (SR_6272_D, Int)}}
let _: Float = SR_6272_D(integerLiteral: 42) + x
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Double'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (SR_6272_D, Int)}}
let _: Float = SR_6272_D(integerLiteral: 42) + 42.0
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (SR_6272_D, Int)}}
let _: Float = SR_6272_D(integerLiteral: 42) + x + 1.0
}
// Ambiguous overload inside a trailing closure
func ambiguousCall() -> Int {} // expected-note {{found this candidate}}
func ambiguousCall() -> Float {} // expected-note {{found this candidate}}
func takesClosure(fn: () -> ()) {}
takesClosure() { ambiguousCall() } // expected-error {{ambiguous use of 'ambiguousCall()'}}
// SR-4692: Useless diagnostics calling non-static method
class SR_4692_a {
private static func foo(x: Int, y: Bool) {
self.bar(x: x)
// expected-error@-1 {{instance member 'bar' cannot be used on type 'SR_4692_a'}}
}
private func bar(x: Int) {
}
}
class SR_4692_b {
static func a() {
self.f(x: 3, y: true)
// expected-error@-1 {{instance member 'f' cannot be used on type 'SR_4692_b'}}
}
private func f(a: Int, b: Bool, c: String) {
self.f(x: a, y: b)
}
private func f(x: Int, y: Bool) {
}
}
// rdar://problem/32101765 - Keypath diagnostics are not actionable/helpful
struct R32101765 { let prop32101765 = 0 }
let _: KeyPath<R32101765, Float> = \.prop32101765
// expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765
// expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
// rdar://problem/32390726 - Bad Diagnostic: Don't suggest `var` to `let` when binding inside for-statement
for var i in 0..<10 { // expected-warning {{variable 'i' was never mutated; consider changing to 'let' constant}} {{5-9=}}
_ = i + 1
}
// rdar://problem/32726044 - shrink reduced domains too far
public protocol P_32726044 {}
extension Int: P_32726044 {}
extension Float: P_32726044 {}
public func *(lhs: P_32726044, rhs: P_32726044) -> Double {
fatalError()
}
func rdar32726044() -> Float {
var f: Float = 0
f = Float(1) * 100 // Ok
let _: Float = Float(42) + 0 // Ok
return f
}
// SR-5045 - Attempting to return result of reduce(_:_:) in a method with no return produces ambiguous error
func sr5045() {
let doubles: [Double] = [1, 2, 3]
return doubles.reduce(0, +)
// expected-error@-1 {{unexpected non-void return value in void function}}
}
// rdar://problem/32934129 - QoI: misleading diagnostic
class L_32934129<T : Comparable> {
init(_ value: T) { self.value = value }
init(_ value: T, _ next: L_32934129<T>?) {
self.value = value
self.next = next
}
var value: T
var next: L_32934129<T>? = nil
func length() -> Int {
func inner(_ list: L_32934129<T>?, _ count: Int) {
guard let list = list else { return count } // expected-error {{unexpected non-void return value in void function}}
return inner(list.next, count + 1)
}
return inner(self, 0) // expected-error {{cannot convert return expression of type '()' to return type 'Int'}}
}
}
// rdar://problem/31671195 - QoI: erroneous diagnostic - cannot call value of non-function type
class C_31671195 {
var name: Int { fatalError() }
func name(_: Int) { fatalError() }
}
C_31671195().name(UInt(0))
// expected-error@-1 {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
// rdar://problem/28456467 - QoI: erroneous diagnostic - cannot call value of non-function type
class AST_28456467 {
var hasStateDef: Bool { return false }
}
protocol Expr_28456467 {}
class ListExpr_28456467 : AST_28456467, Expr_28456467 {
let elems: [Expr_28456467]
init(_ elems:[Expr_28456467] ) {
self.elems = elems
}
override var hasStateDef: Bool {
return elems.first(where: { $0.hasStateDef }) != nil
// expected-error@-1 {{value of type 'Expr_28456467' has no member 'hasStateDef'}}
}
}
// rdar://problem/31849281 - Let's play "bump the argument"
struct rdar31849281 { var foo, a, b, c: Int }
_ = rdar31849281(a: 101, b: 102, c: 103, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(a: 101, c: 103, b: 102, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(foo: 104, a: 101, c: 103, b: 102) // expected-error {{argument 'b' must precede argument 'c'}} {{36-36=b: 102, }} {{42-50=}}
_ = rdar31849281(b: 102, c: 103, a: 101, foo: 104) // expected-error {{incorrect argument labels in call (have 'b:c:a:foo:', expected 'foo:a:b:c:')}} {{18-19=foo}} {{26-27=a}} {{34-35=b}} {{42-45=c}}
_ = rdar31849281(foo: 104, b: 102, c: 103, a: 101) // expected-error {{argument 'a' must precede argument 'b'}} {{28-28=a: 101, }} {{42-50=}}
func var_31849281(_ a: Int, _ b: Int..., c: Int) {}
var_31849281(1, c: 10, 3, 4, 5, 6, 7, 8, 9) // expected-error {{unnamed argument #3 must precede argument 'c'}} {{17-17=3, 4, 5, 6, 7, 8, 9, }} {{22-43=}}
func fun_31849281(a: (Bool) -> Bool, b: (Int) -> (String), c: [Int?]) {}
fun_31849281(c: [nil, 42], a: { !$0 }, b: { (num: Int) -> String in return "\(num)" })
// expected-error @-1 {{incorrect argument labels in call (have 'c:a:b:', expected 'a:b:c:')}} {{14-15=a}} {{28-29=b}} {{40-41=c}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { (num: Int) -> String in return String(describing: num) })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { (num: Int) -> String in return String(describing: num) }, }} {{38-101=}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { "\($0)" })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { "\\($0)" }, }} {{38-54=}}
func f_31849281(x: Int, y: Int, z: Int) {}
f_31849281(42, y: 10, x: 20) // expected-error {{incorrect argument labels in call (have '_:y:x:', expected 'x:y:z:')}} {{12-12=x: }} {{23-24=z}}
func sr5081() {
var a = ["1", "2", "3", "4", "5"]
var b = [String]()
b = a[2...4] // expected-error {{cannot assign value of type 'ArraySlice<String>' to type '[String]'}}
}
func rdar17170728() {
var i: Int? = 1
var j: Int?
var k: Int? = 2
let _ = [i, j, k].reduce(0 as Int?) {
$0 && $1 ? $0! + $1! : ($0 ? $0! : ($1 ? $1! : nil))
// expected-error@-1 {{cannot force unwrap value of non-optional type 'Bool'}} {{18-19=}}
// expected-error@-2 {{cannot force unwrap value of non-optional type 'Bool'}} {{24-25=}}
// expected-error@-3 {{cannot force unwrap value of non-optional type 'Bool'}} {{36-37=}}
// expected-error@-4 {{cannot force unwrap value of non-optional type 'Bool'}} {{48-49=}}
}
let _ = [i, j, k].reduce(0 as Int?) {
$0 && $1 ? $0 + $1 : ($0 ? $0 : ($1 ? $1 : nil))
// expected-error@-1 {{ambiguous use of operator '+'}}
}
}
// https://bugs.swift.org/browse/SR-5934 - failure to emit diagnostic for bad
// generic constraints
func elephant<T, U>(_: T) where T : Collection, T.Element == U, T.Element : Hashable {} // expected-note {{where 'U' = 'T'}}
func platypus<T>(a: [T]) {
_ = elephant(a) // expected-error {{global function 'elephant' requires that 'T' conform to 'Hashable'}}
}
// Another case of the above.
func badTypes() {
let sequence:AnySequence<[Int]> = AnySequence() { AnyIterator() { [3] }}
let array = [Int](sequence)
// expected-error@-1 {{initializer 'init(_:)' requires the types 'Int' and '[Int]' be equivalent}}
}
// rdar://34357545
func unresolvedTypeExistential() -> Bool {
return (Int.self==_{})
// expected-error@-1 {{ambiguous reference to member '=='}}
}
func rdar43525641(_ a: Int, _ b: Int = 0, c: Int = 0, _ d: Int) {}
rdar43525641(1, c: 2, 3) // Ok
| apache-2.0 | e4c81809cdc3b235cdeb2d0352599ef9 | 44.814906 | 240 | 0.663085 | 3.533797 | false | false | false | false |
silence0201/Swift-Study | Learn/13.类继承/构造函数继承.playground/section-1.swift | 1 | 1147 |
import Foundation
class Person {
var name: String
var age: Int
func description() -> String {
return "\(name) 年龄是: \(age)"
}
convenience init() {
self.init(name: "Tony")
self.age = 18
}
convenience init(name: String) {
self.init(name: name, age: 18)
}
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
class Student: Person {
var school: String
init(name: String, age: Int, school: String) {
self.school = school
super.init(name: name, age: age)
}
convenience override init(name: String, age: Int) {
self.init(name: name, age: age, school: "清华大学")
}
}
class Graduate: Student {
var special: String = ""
}
let student1 = Student()
let student2 = Student(name: "Tom")
let student3 = Student(name: "Tom", age: 28)
let student4 = Student(name: "Ben", age: 20, school: "香港大学")
let gstudent1 = Graduate()
let gstudent2 = Graduate(name: "Tom")
let gstudent3 = Graduate(name: "Tom", age: 28)
let gstudent4 = Graduate(name: "Ben", age: 20, school: "香港大学")
| mit | ed755af6f9615234fa3ef3baee60facf | 21.795918 | 62 | 0.589973 | 3.294985 | false | false | false | false |
thachpv91/loafwallet | BreadWallet/BRCameraPlugin.swift | 3 | 12585 | //
// BRCameraPlugin.swift
// BreadWallet
//
// Created by Samuel Sutch on 10/9/16.
// Copyright © 2016 Aaron Voisine. All rights reserved.
//
import Foundation
@available(iOS 8.0, *)
@objc open class BRCameraPlugin: NSObject, BRHTTPRouterPlugin, UIImagePickerControllerDelegate,
UINavigationControllerDelegate, CameraOverlayDelegate {
let controller: UIViewController
var response: BRHTTPResponse?
var picker: UIImagePickerController?
init(fromViewController: UIViewController) {
self.controller = fromViewController
super.init()
}
open func hook(_ router: BRHTTPRouter) {
// GET /_camera/take_picture
//
// Optionally pass ?overlay=<id> (see overlay ids below) to show an overlay
// in picture taking mode
//
// Status codes:
// - 200: Successful image capture
// - 204: User canceled image picker
// - 404: Camera is not available on this device
// - 423: Multiple concurrent take_picture requests. Only one take_picture request may be in flight at once.
//
router.get("/_camera/take_picture") { (request, match) -> BRHTTPResponse in
if self.response != nil {
print("[BRCameraPlugin] already taking a picture")
return BRHTTPResponse(request: request, code: 423)
}
if !UIImagePickerController.isSourceTypeAvailable(.camera)
|| UIImagePickerController.availableCaptureModes(for: .rear) == nil {
print("[BRCameraPlugin] no camera available")
return BRHTTPResponse(request: request, code: 404)
}
let response = BRHTTPResponse(async: request)
self.response = response
DispatchQueue.main.async {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .camera
picker.cameraCaptureMode = .photo
// set overlay
if let overlay = request.query["overlay"] , overlay.count == 1 {
print(["BRCameraPlugin] overlay = \(overlay)"])
let screenBounds = UIScreen.main.bounds
if overlay[0] == "id" {
picker.showsCameraControls = false
picker.allowsEditing = false
picker.hidesBarsOnTap = true
picker.isNavigationBarHidden = true
let overlay = IDCameraOverlay(frame: screenBounds)
overlay.delegate = self
overlay.backgroundColor = UIColor.clear
picker.cameraOverlayView = overlay
}
}
self.picker = picker
self.controller.present(picker, animated: true, completion: nil)
}
return response
}
// GET /_camera/picture/(id)
//
// Return a picture as taken by take_picture
//
// Status codes:
// - 200: Successfully returned iamge
// - 404: Couldn't find image with that ID
//
router.get("/_camera/picture/(id)") { (request, match) -> BRHTTPResponse in
var id: String!
if let ids = match["id"] , ids.count == 1 {
id = ids[0]
} else {
return BRHTTPResponse(request: request, code: 500)
}
let resp = BRHTTPResponse(async: request)
do {
let imgDat = try self.readImage(id)
resp.provide(200, data: imgDat, contentType: "image/jpeg")
} catch let e {
print("[BRCameraPlugin] error reading image: \(e)")
resp.provide(500)
}
return resp
}
}
open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
guard let resp = self.response else {
return
}
defer {
self.response = nil
DispatchQueue.main.async {
picker.dismiss(animated: true, completion: nil)
}
}
resp.provide(204, json: nil)
}
open func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
defer {
DispatchQueue.main.async {
picker.dismiss(animated: true, completion: nil)
}
}
guard let resp = self.response else {
return
}
guard var img = info[UIImagePickerControllerOriginalImage] as? UIImage else {
print("[BRCameraPlugin] error picking image... original image doesnt exist. data: \(info)")
resp.provide(500)
response = nil
return
}
resp.request.queue.async {
defer {
self.response = nil
}
do {
if let overlay = self.picker?.cameraOverlayView as? CameraOverlay {
if let croppedImg = overlay.cropImage(img) {
img = croppedImg
}
}
let id = try self.writeImage(img)
print(["[BRCameraPlugin] wrote image to \(id)"])
resp.provide(200, json: ["id": id])
} catch let e {
print("[BRCameraPlugin] error writing image: \(e)")
resp.provide(500)
}
}
}
func takePhoto() {
self.picker?.takePicture()
}
func cancelPhoto() {
if let picker = self.picker {
self.imagePickerControllerDidCancel(picker)
}
}
func readImage(_ name: String) throws -> [UInt8] {
let fm = FileManager.default
let docsUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first!
let picDirUrl = docsUrl.appendingPathComponent("pictures", isDirectory: true)
let picUrl = picDirUrl.appendingPathComponent("\(name).jpeg")
guard let dat = try? Data(contentsOf: picUrl) else {
throw ImageError.couldntRead
}
let bp = (dat as NSData).bytes.bindMemory(to: UInt8.self, capacity: dat.count)
return Array(UnsafeBufferPointer(start: bp, count: dat.count))
}
func writeImage(_ image: UIImage) throws -> String {
guard let dat = UIImageJPEGRepresentation(image, 0.5) else {
throw ImageError.errorConvertingImage
}
let name = (NSData(uInt256: (dat as NSData).sha256()) as NSData).base58String()
let fm = FileManager.default
let docsUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first!
let picDirUrl = docsUrl.appendingPathComponent("pictures", isDirectory: true)
let picDirPath = picDirUrl.path
var attrs = try? fm.attributesOfItem(atPath: picDirPath)
if attrs == nil {
try fm.createDirectory(atPath: picDirPath, withIntermediateDirectories: true, attributes: nil)
attrs = try fm.attributesOfItem(atPath: picDirPath)
}
let picUrl = picDirUrl.appendingPathComponent("\(name).jpeg")
try dat.write(to: picUrl, options: [])
return name
}
}
enum ImageError: Error {
case errorConvertingImage
case couldntRead
}
protocol CameraOverlayDelegate {
func takePhoto()
func cancelPhoto()
}
protocol CameraOverlay {
func cropImage(_ image: UIImage) -> UIImage?
}
class IDCameraOverlay: UIView, CameraOverlay {
var delegate: CameraOverlayDelegate?
let takePhotoButton: UIButton
let cancelButton: UIButton
let overlayRect: CGRect
override init(frame: CGRect) {
overlayRect = CGRect(x: 0, y: 0, width: frame.width, height: frame.width * CGFloat(4.0/3.0))
takePhotoButton = UIButton(type: .custom)
takePhotoButton.setImage(UIImage(named: "camera-btn"), for: UIControlState())
takePhotoButton.setImage(UIImage(named: "camera-btn-pressed"), for: .highlighted)
takePhotoButton.frame = CGRect(x: 0, y: 0, width: 79, height: 79)
takePhotoButton.center = CGPoint(
x: overlayRect.midX,
y: overlayRect.maxX + (frame.height - overlayRect.maxX) * 0.75
)
cancelButton = UIButton(type: .custom)
cancelButton.setTitle(NSLocalizedString("Cancel", comment: ""), for: UIControlState())
cancelButton.frame = CGRect(x: 0, y: 0, width: 88, height: 44)
cancelButton.center = CGPoint(x: takePhotoButton.center.x * 0.3, y: takePhotoButton.center.y)
cancelButton.setTitleColor(UIColor.white, for: UIControlState())
super.init(frame: frame)
takePhotoButton.addTarget(self, action: #selector(IDCameraOverlay.doTakePhoto(_:)),
for: .touchUpInside)
cancelButton.addTarget(self, action: #selector(IDCameraOverlay.doCancelPhoto(_:)),
for: .touchUpInside)
self.addSubview(cancelButton)
self.addSubview(takePhotoButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) is not implemented")
}
func doTakePhoto(_ target: UIControl) {
delegate?.takePhoto()
}
func doCancelPhoto(_ target: UIControl) {
delegate?.cancelPhoto()
}
override func draw(_ rect: CGRect) {
super.draw(rect)
UIColor.black.withAlphaComponent(0.92).setFill()
UIRectFill(overlayRect)
guard let ctx = UIGraphicsGetCurrentContext() else {
return
}
ctx.setBlendMode(.destinationOut)
let width = rect.size.width * 0.9
var cutout = CGRect(origin: overlayRect.origin,
size: CGSize(width: width, height: width * 0.65))
cutout.origin.x = (overlayRect.size.width - cutout.size.width) * 0.5
cutout.origin.y = (overlayRect.size.height - cutout.size.height) * 0.5
let path = UIBezierPath(rect: cutout.integral)
path.fill()
ctx.setBlendMode(.normal)
let str = NSLocalizedString("Center your ID in the box", comment: "") as NSString
let style = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
style.alignment = .center
let attr = [
NSParagraphStyleAttributeName: style,
NSFontAttributeName: UIFont.boldSystemFont(ofSize: 17),
NSForegroundColorAttributeName: UIColor.white
]
str.draw(in: CGRect(x: 0, y: cutout.maxY + 14.0, width: rect.width, height: 22), withAttributes: attr)
}
func cropImage(_ image: UIImage) -> UIImage? {
guard let cgimg = image.cgImage else {
return nil
}
let rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let width = rect.size.width * 0.9
var cutout = CGRect(origin: rect.origin,
size: CGSize(width: width, height: width * 0.65))
cutout.origin.x = (rect.size.width - cutout.size.width) * 0.5
cutout.origin.y = (rect.size.height - cutout.size.height) * 0.5
cutout = cutout.integral
func rad(_ f: CGFloat) -> CGFloat {
return f / 180.0 * CGFloat(M_PI)
}
var transform: CGAffineTransform!
switch image.imageOrientation {
case .left:
transform = CGAffineTransform(rotationAngle: rad(90)).translatedBy(x: 0, y: -image.size.height)
case .right:
transform = CGAffineTransform(rotationAngle: rad(-90)).translatedBy(x: -image.size.width, y: 0)
case .down:
transform = CGAffineTransform(rotationAngle: rad(-180)).translatedBy(x: -image.size.width,
y: -image.size.height)
default:
transform = CGAffineTransform.identity
}
transform = transform.scaledBy(x: image.scale, y: image.scale)
cutout = cutout.applying(transform)
guard let retRef = cgimg.cropping(to: cutout) else {
return nil
}
return UIImage(cgImage: retRef, scale: image.scale, orientation: image.imageOrientation)
}
}
| mit | 4bbeff05ac0c2a8ee20aeeef824f44b9 | 38.080745 | 118 | 0.569215 | 4.871854 | false | false | false | false |
jeroendesloovere/examples-swift | Swift-Playgrounds/UsingSwiftWithCocoaAndObjective-C/AdoptingCocoaDesignPatterns.playground/section-1.swift | 1 | 2590 | // Adopting Cocoa Design Patterns
import Cocoa
// Delegation
/*
if let fullScreenSize = myDelegate?.window?(myWindow, willUseFullScreenContentSize: mySize) {
println(NSStringFromSize(fullScreenSize))
}
*/
// 1. Check that myDelegate is not nil.
// 2. Check that myDelegate implements the method window:willUseFullScreenContentSize:.
// 3. If 1 and 2 hold true, invoke the method and assign the result of the method to the value named fullScreenSize.
// 4. Print the return value of the method.
// In a pure Swift app, type the delegate property as an optional NSWindowDelegate object and assign it an initial value of nil.
// Error Reporting
// Error reporting in Swift follows the same pattern it does in Objective-C.
// In the simplest case, you return a Bool value from the function to indicate whether or not it succeeded.
// When you need to report the reason for the error, you can add to the function an NSError out parameter of type NSErrorPointer. This type is roughly equivalent to Objective-C’s NSError **. You can use the prefix & operator to pass in a reference to an optional NSError type as an NSErrorPointer object, as shown in the code listing below.
/*
var writeError: NSError?
let written = myString.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: &writeError)
if !written {
if let error = writeError {
println("write failure: \(error.localizedDescription)")
}
}
*/
func contentsForType(typeName: String!, error: NSErrorPointer) -> AnyObject! {
let errorOccured = true
//if cannotProduceContentsForType(typeName) {
if errorOccured {
if error {
error.memory = NSError(domain: NSPOSIXErrorDomain, code: 1, userInfo: [:])
}
return nil
}
}
var errorPointer: NSErrorPointer = NSErrorPointer()
let typeName = "JPEG"
contentsForType(typeName, errorPointer)
// Target-Action
// Basically the same as in Objective-C
// Introspection
// In ObjC you use isKindOfClass: and conformsToProtocol:
// In Swift you use the is operator and the as? operator to downcast
/*if errorPointer is NSButton {
println("\(typeName) is a string")
} else {
println("typeName is not a string")
}
if let button = errorPointer as? NSErrorPointer {
}
*/
// Checking for and casting to a protocol follows exactly the same syntax as checking for and casting to a class.
/*
if let dataSource = object as? UITableViewDataSource {
// object conforms to UITableViewDataSource and is bound to dataSource
} else {
// object not conform to UITableViewDataSource
}
*/
| mit | 914715a18b74ed94d690443ac3a5c916 | 32.179487 | 341 | 0.733385 | 4.416382 | false | false | false | false |
jungtong/LernaFramework | Pod/Classes/LernaUtil.swift | 1 | 1954 | //
// LernaUtil.swift
// Pods
//
// Created by jungtong on 2016. 1. 5..
//
//
import Foundation
public class LernaUtil {
public class func objectToJSONString(object: AnyObject) throws -> String? {
let resultJSONString: String?
do {
let jsonData: NSData = try NSJSONSerialization.dataWithJSONObject(object, options: NSJSONWritingOptions(rawValue:0))
resultJSONString = NSString(data: jsonData, encoding:NSUTF8StringEncoding) as? String
}
catch let error {
throw error
}
return resultJSONString
}
public class func JSONDataToObject(data: NSData) throws -> AnyObject? {
let resultObject: AnyObject?
do {
resultObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
}
catch let error {
throw error
}
return resultObject
}
public class func getCurrentDataTime() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyyMMddHHmm"
return dateFormatter.stringFromDate(NSDate())
}
public class func diffWithCurrentTime(dateTime: String) -> Int {
let inputDateTimeComponent = NSDateComponents()
inputDateTimeComponent.year = Int(dateTime.substringWithIntRange(0...3))!
inputDateTimeComponent.month = Int(dateTime.substringWithIntRange(4...5))!
inputDateTimeComponent.day = Int(dateTime.substringWithIntRange(6...7))!
inputDateTimeComponent.hour = Int(dateTime.substringWithIntRange(8...9))!
inputDateTimeComponent.minute = Int(dateTime.substringWithIntRange(10...11))!
let inputDateTime = NSCalendar.currentCalendar().dateFromComponents(inputDateTimeComponent)!
let diffDate: NSTimeInterval = NSDate().timeIntervalSinceDate(inputDateTime)
return Int(diffDate / 60)
}
} | mit | ef1ab36254e4c7968da78421319ec467 | 35.203704 | 128 | 0.668884 | 5.010256 | false | false | false | false |
nalexn/ViewInspector | Tests/ViewInspectorTests/ViewModifiers/CustomStyleModifiersTests.swift | 1 | 4906 | import XCTest
import SwiftUI
@testable import ViewInspector
// MARK: - CustomStyleModifiersTests
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
final class CustomStyleModifiersTests: XCTestCase {
func testHelloWorldStyle() throws {
let sut = EmptyView().helloWorldStyle(RedOutlineHelloWorldStyle())
XCTAssertNoThrow(try sut.inspect().emptyView())
print(type(of: sut))
}
func testHelloWorldStyleInspection() throws {
let sut = EmptyView().helloWorldStyle(RedOutlineHelloWorldStyle())
XCTAssertTrue(try sut.inspect().customStyle("helloWorldStyle") is RedOutlineHelloWorldStyle)
}
func testHelloWorldStyleExtraction() throws {
let style = DefaultHelloWorldStyle()
XCTAssertNoThrow(try style.inspect().zStack())
}
func testHelloWorldStyleAsyncInspection() throws {
let style = RedOutlineHelloWorldStyle()
var body = try style.inspect().view(RedOutlineHelloWorldStyle.StyleBody.self).actualView()
let expectation = body.on(\.didAppear) { inspectedBody in
let zStack = try inspectedBody.zStack()
let rectangle = try zStack.shape(0)
XCTAssertEqual(try rectangle.fillShapeStyle(Color.self), Color.red)
XCTAssertEqual(try rectangle.strokeStyle().lineWidth, 1)
XCTAssertEqual(try rectangle.fillStyle().isAntialiased, true)
}
ViewHosting.host(view: body, size: CGSize(width: 300, height: 300))
wait(for: [expectation], timeout: 1.0)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
struct HelloWorldStyleConfiguration {}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
protocol HelloWorldStyle {
associatedtype Body: View
typealias Configuration = HelloWorldStyleConfiguration
func makeBody(configuration: Self.Configuration) -> Self.Body
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
struct DefaultHelloWorldStyle: HelloWorldStyle {
func makeBody(configuration: HelloWorldStyleConfiguration) -> some View {
ZStack {
Rectangle()
.strokeBorder(Color.accentColor, lineWidth: 1, antialiased: true)
}
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
struct RedOutlineHelloWorldStyle: HelloWorldStyle {
func makeBody(configuration: HelloWorldStyleConfiguration) -> some View {
StyleBody(configuration: configuration)
}
struct StyleBody: View {
let configuration: HelloWorldStyleConfiguration
internal var didAppear: ((Self) -> Void)?
var body: some View {
ZStack {
Rectangle()
.strokeBorder(Color.red, lineWidth: 1, antialiased: true)
}
.onAppear { self.didAppear?(self) }
}
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
struct HelloWorldStyleKey: EnvironmentKey {
static var defaultValue: AnyHelloWorldStyle = AnyHelloWorldStyle(DefaultHelloWorldStyle())
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension EnvironmentValues {
var style: AnyHelloWorldStyle {
get { self[HelloWorldStyleKey.self] }
set { self[HelloWorldStyleKey.self] = newValue }
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
struct AnyHelloWorldStyle: HelloWorldStyle {
private var _makeBody: (HelloWorldStyle.Configuration) -> AnyView
init<S: HelloWorldStyle>(_ style: S) {
_makeBody = { configuration in
AnyView(style.makeBody(configuration: configuration))
}
}
func makeBody(configuration: HelloWorldStyle.Configuration) -> some View {
_makeBody(configuration)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
struct HelloWorldStyleModifier<S: HelloWorldStyle>: ViewModifier {
let style: S
init(_ style: S) {
self.style = style
}
func body(content: Self.Content) -> some View {
content
.environment(\.style, AnyHelloWorldStyle(style))
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension View {
func helloWorldStyle<S: HelloWorldStyle>(_ style: S) -> some View {
modifier(HelloWorldStyleModifier(style))
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension DefaultHelloWorldStyle {
func inspect() throws -> InspectableView<ViewType.ClassifiedView> {
let configuration = HelloWorldStyleConfiguration()
return try makeBody(configuration: configuration).inspect()
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension RedOutlineHelloWorldStyle {
func inspect() throws -> InspectableView<ViewType.ClassifiedView> {
let configuration = HelloWorldStyleConfiguration()
return try makeBody(configuration: configuration).inspect()
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension RedOutlineHelloWorldStyle.StyleBody: Inspectable {}
| mit | f75e47e47fb31909f1c61a894974f73c | 31.706667 | 100 | 0.67285 | 4.299737 | false | true | false | false |
mcBontempi/PersonalBrand | PersonalBrand/PersonalBrand/AppDelegate.swift | 1 | 6104 | //
// AppDelegate.swift
// PersonalBrand
//
// Created by Daren David Taylor on 13/05/2016.
// Copyright © 2016 DDT. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.DDT.PersonalBrand" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("PersonalBrand", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| gpl-3.0 | d9fd6fd4573adb67a400949da1541c2e | 53.981982 | 291 | 0.719974 | 5.896618 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | 37--Resurgence/VenueMenu/VenueMenu/AppDelegate.swift | 1 | 6183 | //
// AppDelegate.swift
// VenueMenu
//
// Created by Pedro Trujillo on 11/24/15.
// Copyright © 2015 Pedro Trujillo. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.tiy.VenueMenu" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("VenueMenu", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
//raference [1] http://stackoverflow.com/questions/16593431/nsdictionary-and-core-data | cc0-1.0 | becb7970a87fb48dc50ec33c558fafa4 | 54.205357 | 291 | 0.720964 | 5.832075 | false | false | false | false |
WenkyYuan/SwiftDemo | SwiftDemo/Controllers/NextViewController.swift | 1 | 1332 | //
// NextViewController.swift
// SwiftDemo
//
// Created by wenky on 15/11/19.
// Copyright (c) 2015年 wenky. All rights reserved.
//
import UIKit
class NextViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
let url: String = "http://www.baidu.com" //初始化为百度网址字符串,常量
var bgColor: UIColor? //初始化为nil,因为生命周期中,(理想状态)可能为nil所以用?
deinit {
NSLog("dealloc")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Next"
view.backgroundColor = bgColor==nil ? UIColor.redColor() : bgColor
setupNavBarItem()
setupWebView()
}
func setupNavBarItem() {
let item: UIBarButtonItem = UIBarButtonItem(title: "通知", style: UIBarButtonItemStyle.Plain, target: self, action: "didTapBar")
navigationItem.rightBarButtonItem = item
}
func setupWebView() {
let webUrl: NSURL! = NSURL(string: url)
let request: NSURLRequest = NSURLRequest(URL: webUrl)
webView.loadRequest(request)
}
func didTapBar() {
NSNotificationCenter.defaultCenter().postNotificationName("kNotificationName", object: nil)
navigationController?.popViewControllerAnimated(true)
}
} | mit | 8e5679802b3b0533f0093bb0601ae30c | 26.888889 | 134 | 0.643541 | 4.446809 | false | false | false | false |
between40and2/XALG | frameworks/Framework-XALG/Tree/Algo/XALG_Algo_BinaryTree_Traversal.swift | 1 | 1318 | //
// XALG_Algo_BinaryTree_Traversal.swift
// XALG
//
// Created by Juguang Xiao on 02/03/2017.
//
import Swift
class XALG_Algo_BinaryTree_Traversal<TreeType>
where TreeType : XALG_ADT_Tree_BinaryTree,
TreeType.NodeType == TreeType.NodeType.NodeType
{
typealias NodeType = TreeType.NodeType
typealias XALG_Block_BinaryTreeNode = (NodeType) -> Void
enum TraversalOrder {
case preorder
case inorder
case postorder
// case levelorder
}
static func travel__recursive(_ root: NodeType? , order : TraversalOrder = .preorder, visit : XALG_Block_BinaryTreeNode) {
guard let n = root else {
return
}
switch order {
case .preorder:
visit(n)
travel__recursive(n.lchild, order: order, visit: visit)
travel__recursive(n.rchild, order: order, visit: visit)
case .inorder :
travel__recursive(n.lchild, order: order, visit: visit)
visit(n)
travel__recursive(n.rchild, order: order, visit: visit)
case .postorder :
travel__recursive(n.lchild, order: order, visit: visit)
travel__recursive(n.rchild, order: order, visit: visit)
visit(n)
}
}
}
| mit | 44f7700368fe7fbfb0fd92735ca36ba8 | 23.407407 | 126 | 0.582701 | 4.030581 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalMessaging/ViewControllers/Stickers/StickerPackCollectionView.swift | 1 | 11056 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import YYImage
@objc
public protocol StickerPackCollectionViewDelegate {
func didTapSticker(stickerInfo: StickerInfo)
func stickerPreviewHostView() -> UIView?
func stickerPreviewHasOverlay() -> Bool
}
// MARK: -
@objc
public class StickerPackCollectionView: UICollectionView {
private var stickerPackDataSource: StickerPackDataSource? {
didSet {
AssertIsOnMainThread()
stickerPackDataSource?.add(delegate: self)
reloadStickers()
// Scroll to the top.
contentOffset = .zero
}
}
private var stickerInfos = [StickerInfo]()
public var stickerCount: Int {
return stickerInfos.count
}
@objc
public weak var stickerDelegate: StickerPackCollectionViewDelegate?
@objc
override public var frame: CGRect {
didSet {
updateLayout()
}
}
@objc
override public var bounds: CGRect {
didSet {
updateLayout()
}
}
private let cellReuseIdentifier = "cellReuseIdentifier"
@objc
public required init() {
super.init(frame: .zero, collectionViewLayout: StickerPackCollectionView.buildLayout())
delegate = self
dataSource = self
register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellReuseIdentifier)
isUserInteractionEnabled = true
addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress)))
}
// MARK: Modes
@objc
public func showInstalledPack(stickerPack: StickerPack) {
AssertIsOnMainThread()
self.stickerPackDataSource = InstalledStickerPackDataSource(stickerPackInfo: stickerPack.info)
}
@objc
public func showUninstalledPack(stickerPack: StickerPack) {
AssertIsOnMainThread()
self.stickerPackDataSource = TransientStickerPackDataSource(stickerPackInfo: stickerPack.info,
shouldDownloadAllStickers: true)
}
@objc
public func showRecents() {
AssertIsOnMainThread()
self.stickerPackDataSource = RecentStickerPackDataSource()
}
public func showInstalledPackOrRecents(stickerPack: StickerPack?) {
if let stickerPack = stickerPack {
showInstalledPack(stickerPack: stickerPack)
} else {
showRecents()
}
}
func show(dataSource: StickerPackDataSource) {
AssertIsOnMainThread()
self.stickerPackDataSource = dataSource
}
// MARK: Events
required public init(coder: NSCoder) {
notImplemented()
}
private func reloadStickers() {
AssertIsOnMainThread()
guard let stickerPackDataSource = stickerPackDataSource else {
stickerInfos = []
return
}
stickerInfos = stickerPackDataSource.installedStickerInfos
reloadData()
}
@objc
func handleLongPress(sender: UIGestureRecognizer) {
guard let indexPath = self.indexPathForItem(at: sender.location(in: self)) else {
hidePreview()
return
}
guard let stickerInfo = stickerInfos[safe: indexPath.row] else {
owsFailDebug("Invalid index path: \(indexPath)")
hidePreview()
return
}
switch sender.state {
case .began, .changed:
break
case .possible, .ended, .cancelled, .failed:
fallthrough
@unknown default:
hidePreview()
return
}
ensurePreview(stickerInfo: stickerInfo)
}
private var previewView: UIView?
private var previewStickerInfo: StickerInfo?
private func hidePreview() {
AssertIsOnMainThread()
previewView?.removeFromSuperview()
previewView = nil
previewStickerInfo = nil
}
private func ensurePreview(stickerInfo: StickerInfo) {
AssertIsOnMainThread()
if previewView != nil,
let previewStickerInfo = previewStickerInfo,
previewStickerInfo == stickerInfo {
// Already showing a preview for this sticker.
return
}
hidePreview()
guard let stickerView = imageView(forStickerInfo: stickerInfo) else {
owsFailDebug("Couldn't load sticker for display")
return
}
guard let stickerDelegate = stickerDelegate else {
owsFailDebug("Missing stickerDelegate")
return
}
guard let hostView = stickerDelegate.stickerPreviewHostView() else {
owsFailDebug("Missing host view.")
return
}
if stickerDelegate.stickerPreviewHasOverlay() {
let overlayView = UIView()
overlayView.backgroundColor = Theme.backgroundColor.withAlphaComponent(0.5)
hostView.addSubview(overlayView)
overlayView.autoPinEdgesToSuperviewEdges()
overlayView.setContentHuggingLow()
overlayView.setCompressionResistanceLow()
overlayView.addSubview(stickerView)
previewView = overlayView
} else {
hostView.addSubview(stickerView)
previewView = stickerView
}
previewStickerInfo = stickerInfo
stickerView.autoPinToSquareAspectRatio()
stickerView.autoCenterInSuperview()
let vMargin: CGFloat = 40
let hMargin: CGFloat = 60
stickerView.autoSetDimension(.width, toSize: hostView.height() - vMargin * 2, relation: .lessThanOrEqual)
stickerView.autoPinEdge(toSuperviewEdge: .top, withInset: vMargin, relation: .greaterThanOrEqual)
stickerView.autoPinEdge(toSuperviewEdge: .bottom, withInset: vMargin, relation: .greaterThanOrEqual)
stickerView.autoPinEdge(toSuperviewEdge: .leading, withInset: hMargin, relation: .greaterThanOrEqual)
stickerView.autoPinEdge(toSuperviewEdge: .trailing, withInset: hMargin, relation: .greaterThanOrEqual)
}
private func imageView(forStickerInfo stickerInfo: StickerInfo) -> UIView? {
guard let stickerPackDataSource = stickerPackDataSource else {
owsFailDebug("Missing stickerPackDataSource.")
return nil
}
guard let filePath = stickerPackDataSource.filePath(forSticker: stickerInfo) else {
owsFailDebug("Missing sticker data file path.")
return nil
}
guard NSData.ows_isValidImage(atPath: filePath, mimeType: OWSMimeTypeImageWebp) else {
owsFailDebug("Invalid sticker.")
return nil
}
guard let stickerImage = YYImage(contentsOfFile: filePath) else {
owsFailDebug("Sticker could not be parsed.")
return nil
}
let stickerView = YYAnimatedImageView()
stickerView.image = stickerImage
return stickerView
}
}
// MARK: - UICollectionViewDelegate
extension StickerPackCollectionView: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
Logger.debug("")
guard let stickerInfo = stickerInfos[safe: indexPath.row] else {
owsFailDebug("Invalid index path: \(indexPath)")
return
}
self.stickerDelegate?.didTapSticker(stickerInfo: stickerInfo)
}
}
// MARK: - UICollectionViewDataSource
extension StickerPackCollectionView: UICollectionViewDataSource {
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection sectionIdx: Int) -> Int {
return stickerInfos.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// We could eventually use cells that lazy-load the sticker views
// when the cells becomes visible and eagerly unload them.
// But we probably won't need to do that.
let cell = dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath)
for subview in cell.contentView.subviews {
subview.removeFromSuperview()
}
guard let stickerInfo = stickerInfos[safe: indexPath.row] else {
owsFailDebug("Invalid index path: \(indexPath)")
return cell
}
guard let stickerView = imageView(forStickerInfo: stickerInfo) else {
owsFailDebug("Couldn't load sticker for display")
return cell
}
cell.contentView.addSubview(stickerView)
stickerView.autoPinEdgesToSuperviewEdges()
let accessibilityName = "sticker." + stickerInfo.asKey()
cell.accessibilityIdentifier = UIView.accessibilityIdentifier(in: self, name: accessibilityName + ".cell")
stickerView.accessibilityIdentifier = UIView.accessibilityIdentifier(in: self, name: accessibilityName + ".item")
return cell
}
}
// MARK: - Layout
extension StickerPackCollectionView {
// TODO:
static let kSpacing: CGFloat = 8
private class func buildLayout() -> UICollectionViewFlowLayout {
let layout = UICollectionViewFlowLayout()
if #available(iOS 11, *) {
layout.sectionInsetReference = .fromSafeArea
}
layout.minimumInteritemSpacing = kSpacing
layout.minimumLineSpacing = kSpacing
let inset = kSpacing
layout.sectionInset = UIEdgeInsets(top: inset, leading: inset, bottom: inset, trailing: inset)
return layout
}
// TODO: There's pending design Qs here.
func updateLayout() {
guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else {
// The layout isn't set while the view is being initialized.
return
}
let containerWidth: CGFloat
if #available(iOS 11.0, *) {
containerWidth = self.safeAreaLayoutGuide.layoutFrame.size.width
} else {
containerWidth = self.frame.size.width
}
let spacing = StickerPackCollectionView.kSpacing
let inset = spacing
let preferredCellSize: CGFloat = 80
let contentWidth = containerWidth - 2 * inset
let columnCount = UInt((contentWidth + spacing) / (preferredCellSize + spacing))
let cellWidth = (contentWidth - spacing * (CGFloat(columnCount) - 1)) / CGFloat(columnCount)
let itemSize = CGSize(width: cellWidth, height: cellWidth)
if (itemSize != flowLayout.itemSize) {
flowLayout.itemSize = itemSize
flowLayout.invalidateLayout()
}
}
}
// MARK: -
extension StickerPackCollectionView: StickerPackDataSourceDelegate {
public func stickerPackDataDidChange() {
AssertIsOnMainThread()
reloadStickers()
}
}
| gpl-3.0 | 24abaa0caa124b0a2e65ef26fc1f60fc | 30.05618 | 128 | 0.650778 | 5.746362 | false | false | false | false |
Guferos/pocketWikiApp | Wikipedia/WikipediaAPI.swift | 1 | 9553 | //
// WikipediaAPI.swift
// Wikipedia
//
// Created by Damian on 04/11/2014.
// Copyright (c) 2014 Damian Wojtczak. All rights reserved.
//
import Foundation
import UIKit
struct WikiSuggestions {
var key : String
var titles : Array<String>
}
class WikiPage {
var pageID : Int
var thumbnailURL : NSURL?
var title : String
var pageURL : NSURL?
var lastUpdated : NSDate?
private var image : UIImage?
init(pageID : Int, thumbnailURL : NSURL?, title : String, pageURL: NSURL?) {
self.pageID = pageID
self.thumbnailURL = thumbnailURL
self.title = title
self.pageURL = pageURL
}
//Get WikiPage thumbnail from local cache or download it from web
func getThumbImage() -> (UIImage?) {
//If image exist return image
if (self.image != nil) {
return self.image
}
else {
//Check if URL is available
if (thumbnailURL != nil) {
//Check if image was cached before
var fm = NSFileManager.defaultManager()
var cacheDir = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0] as String
var filename = thumbnailURL!.absoluteString!.stringByReplacingOccurrencesOfString("/", withString: "_")
var fullPath = cacheDir.stringByAppendingPathComponent(filename)
if (fm.fileExistsAtPath(fullPath)) {
self.image = UIImage(contentsOfFile: fullPath)
}
//Load image from web if not cached
else {
if let data = NSData(contentsOfURL: self.thumbnailURL!) {
let saveSucceded = data.writeToFile(fullPath, atomically: true)
if (!saveSucceded) {
println("Saving failed for file: \(fullPath)")
}
self.image = UIImage(data: data)
}
}
return self.image
}
else {
return nil
}
}
}
}
class WikipediaAPI {
class func getSearchSuggestions(key: String, limit: Int, completion : (error: NSError?, data: WikiSuggestions?)->()) {
//Create request URL and add GET parameters
var urlString = "http://en.wikipedia.org/w/api.php?action=opensearch&search=\(key.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)&limit=\(limit)&namespace=0&format=json"
if let url = NSURL(string: urlString) {
//Create request and NSURLSession with default configuration
var request: NSURLRequest = NSURLRequest(URL:url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
//Execute request
session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
//Handle response error
if (error != nil) {
completion(error: error, data: nil)
}
else {
//Serialize JSON
var jsonError : NSError?
var jsonData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as NSArray
//Handle JSON error
if (jsonError != nil) {
completion(error: jsonError, data: nil)
}
else {
//Create Wiki Suggestion object and call completion callback
var result = WikiSuggestions(key: jsonData[0] as String, titles: jsonData[1] as Array<String>)
completion(error: nil, data: result)
}
}
}).resume();
}
else {
//Handle error
var userInfo = NSDictionary(object: NSLocalizedDescriptionKey, forKey: "Failed to create URL")
var error : NSError = NSError(domain: "", code: 0, userInfo: userInfo)
completion(error: error, data: nil)
}
}
class func getSearchResults(key: String, limit: Int, completion : (error: NSError?, data: Array<WikiPage>?)->()) {
//Escape special characters with percent encoding
var escapedKey = key.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
//Create request URL with all GET parameters
var urlString = "http://en.wikipedia.org/w/api.php?"
urlString += "format=json"
urlString += "&action=query"
urlString += "&generator=prefixsearch"
urlString += "&gpssearch=\(escapedKey!)"
urlString += "&gpsnamespace=0"
urlString += "&gpslimit=\(limit)"
urlString += "&prop=pageimages%7Cinfo"
urlString += "&piprop=thumbnail"
urlString += "&pithumbsize=80"
urlString += "&pilimit=\(limit)"
urlString += "&list=prefixsearch"
urlString += "&pssearch=\(escapedKey!)"
urlString += "&pslimit=\(limit)"
urlString += "&inprop=url"
if let url = NSURL(string: urlString) {
//Create request and NSURLSession with default configuration
var request: NSURLRequest = NSURLRequest(URL:url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
//Execute request
session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
//Handle response error
if (error != nil) {
completion(error: error, data: nil)
}
else {
//Serialize JSON
var jsonError : NSError?
var jsonData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as NSDictionary
//Handle JSON error
if (jsonError != nil) {
completion(error: jsonError, data: nil)
}
else {
var wikiPages = [WikiPage]()
//Set date format for touched param
var df = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
//Map JSON to custom object
if let query = jsonData.objectForKey("query") as? NSDictionary {
if let pages = query.objectForKey("pages") as? NSDictionary {
if let prefixsearch = query.objectForKey("prefixsearch") as? NSArray {
for (var i=0; i < prefixsearch.count; i++) {
if let item = prefixsearch[i] as? NSDictionary {
if let pageID = item.objectForKey("pageid") as? Int {
if let details = pages.objectForKey("\(pageID)") as? NSDictionary {
if let pageTitle = details.objectForKey("title") as? String {
var newWikiPage = WikiPage(pageID: pageID, thumbnailURL: nil, title: pageTitle, pageURL: nil)
if let thumbnail = details.objectForKey("thumbnail") as? NSDictionary {
if let source = thumbnail.objectForKey("source") as? String {
newWikiPage.thumbnailURL = NSURL(string: source)
}
}
if let fullURL = details.objectForKey("fullurl") as? String {
newWikiPage.pageURL = NSURL(string: fullURL)
}
if let lastUpdated = details.objectForKey("touched") as? String {
newWikiPage.lastUpdated = df.dateFromString(lastUpdated)
}
wikiPages.append(newWikiPage)
}
}
}
}
}
}
}
}
completion(error: nil, data: wikiPages)
}
}
}).resume()
}
else {
var userInfo = NSDictionary(object: NSLocalizedDescriptionKey, forKey: "Failed to create URL")
var error : NSError = NSError(domain: "", code: 0, userInfo: userInfo)
completion(error: error, data: nil)
}
}
}
| mit | fba3e7d3d421d8340efa13aa7659e3c3 | 45.6 | 195 | 0.485083 | 6.084713 | false | true | false | false |
Boris-Em/Goban | Goban/SGFPValueTypeParser.swift | 1 | 4007 | //
// SGFP.ValueTypeParser.swift
// GobanSampleProject
//
// Created by John on 5/5/16.
// Copyright © 2016 Boris Emorine. All rights reserved.
//
import Foundation
struct SGFPValueTypeParser {
static func digitParser() -> CharacterParser<Character> {
return parseCharacterFromSet(CharacterSet.decimalDigits)
}
static func digitsParser() -> CharacterParser<[Character]> {
return parseGreedyCharactersFromSet(CharacterSet.decimalDigits)
}
static func numberStringParser() -> CharacterParser<String> {
let parserPlusMinus = optional(parseCharacter("+") <|> parseCharacter("-"))
func plusMinusToString(_ plusMinus: Character?, digits: [Character]) -> String {
return plusMinus == nil ? String(digits) : (String(describing: plusMinus) + String(digits))
}
return curry(plusMinusToString) </> parserPlusMinus <*> digitsParser()
}
static func numberParser() -> CharacterParser<SGFP.ValueType> {
return { SGFP.ValueType.number(value: Int($0)!) } </> numberStringParser()
}
static func realParser() -> CharacterParser<SGFP.ValueType> {
return curry { SGFPValueTypeParser.realFromWholeDigits($0, fractionDigits: $1) } </> numberStringParser() <*> optional(parseCharacter(".") *> oneOrMore(digitParser()))
}
static func doubleParser() -> CharacterParser<SGFP.ValueType> {
return { SGFP.ValueType.double(value: $0) } </> (parseCharacter("1") <|> parseCharacter("2"))
}
static func colorParser() -> CharacterParser<SGFP.ValueType> {
return { SGFP.ValueType.color(colorName: String($0)) } </> (parseCharacter("B") <|> parseCharacter("W"))
}
static func simpleTextParser() -> CharacterParser<SGFP.ValueType> {
let anythingButBracket = CharacterSet(charactersIn: "]").inverted
return { SGFP.ValueType.simpleText(text: String($0)) } </> parseGreedyCharactersFromSet(anythingButBracket)
}
static func textParser() -> CharacterParser<SGFP.ValueType> {
let anythingButBracket = CharacterSet(charactersIn: "]").inverted
return { SGFP.ValueType.text(text: String($0)) } </> parseGreedyCharactersFromSet(anythingButBracket)
}
static func goPointParser() -> CharacterParser<SGFP.ValueType> {
let parseLcLetter = parseCharacterFromSet(CharacterSet.lowercaseLetters)
return curry { SGFP.ValueType.point(column: $0, row: $1) } </> parseLcLetter <*> parseLcLetter
}
static func goCompressedPointsParser() -> CharacterParser<SGFP.ValueType> {
let parseColon = parseCharacter(":")
return curry { SGFP.ValueType.compressedPoints(upperLeft: $0, lowerRight: $1) } </> goPointParser() <* parseColon <*> goPointParser()
}
static func goMoveParser() -> CharacterParser<SGFP.ValueType> {
let parseLcLetter = parseCharacterFromSet(CharacterSet.lowercaseLetters)
return curry { SGFP.ValueType.move(column: $0, row: $1) } </> parseLcLetter <*> parseLcLetter
}
static func goStoneParser() -> CharacterParser<SGFP.ValueType> {
let parseLcLetter = parseCharacterFromSet(CharacterSet.lowercaseLetters)
return curry { SGFP.ValueType.stone(column: $0, row: $1) } </> parseLcLetter <*> parseLcLetter
}
static func anyValueParser() -> CharacterParser<SGFP.ValueType> {
return numberParser() <|> realParser() <|> doubleParser() <|> colorParser() <|> goPointParser() <|> goMoveParser() <|> goStoneParser() <|> simpleTextParser() <|> textParser()
}
fileprivate static func realFromWholeDigits(_ wholeDigits: String, fractionDigits: [Character]?) -> SGFP.ValueType {
let wholeChars = String(wholeDigits)
let fractionChars = fractionDigits != nil ? String(fractionDigits!) : ""
let realString = wholeChars + "." + fractionChars
let real = Float(realString)!
return SGFP.ValueType.real(value: real)
}
}
| mit | eedc828f32f69034ed41ad7ac044a97d | 42.543478 | 183 | 0.667249 | 4.411894 | false | false | false | false |
steveEECSrubin/studies | iOS_development/udemy_ios8_adn_swift/how_many_fingers.swift | 1 | 1284 | //
// ViewController.swift
// how_many_fingers
//
// Created by Apple on 1/1/16.
// Copyright © 2016 hello_world. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label_answer: UILabel!
@IBOutlet weak var text_input_guess: UITextField!
@IBAction func button_guess(sender: AnyObject)
{
let random_number = arc4random_uniform(6)
//label_answer.text = String(random_number)
let user_guess = Int(text_input_guess.text!)
if(user_guess != nil && user_guess <= 5)
{
if(Int(random_number) == user_guess)
{
label_answer.text = "You guessed correctly :)"
}
else
{
label_answer.text = "You guessed incorrectly :("
}
}
else
{
label_answer.text = "You did not enter any number 0-5"
}
}
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.
}
}
| unlicense | b4ede4c2933b2d83077f8878c1898b4d | 23.207547 | 80 | 0.556508 | 4.393836 | false | false | false | false |
ls1intum/sReto | Source/sReto/Modules/RemoteModule/RemoteP2PPacket.swift | 1 | 2101 | //
// RemoteP2PPacket.swift
// sReto
//
// Created by Julian Asamer on 07/08/14.
// Copyright (c) 2014 - 2016 Chair for Applied Software Engineering
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness
// for a particular purpose and noninfringement. in no event shall the authors or copyright holders be liable for any claim, damages or other liability,
// whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.
//
import Foundation
enum RemoteP2PPacketType: Int32 {
case startAdvertisement = 1
case stopAdvertisement = 2
case startBrowsing = 3
case stopBrowsing = 4
case peerAdded = 5
case peerRemoved = 6
case connectionRequest = 7
}
struct RemoteP2PPacket {
let type: RemoteP2PPacketType
let identifier: UUID
static func fromData(_ data: DataReader) -> RemoteP2PPacket? {
let type = RemoteP2PPacketType(rawValue: data.getInteger())
if type == nil { return nil }
if !data.checkRemaining(16) { return nil }
return RemoteP2PPacket(type: type!, identifier: data.getUUID())
}
func serialize() -> Data {
let data = DataWriter(length: 20)
data.add(self.type.rawValue)
data.add(self.identifier)
return data.getData() as Data
}
}
| mit | 522009820adcef8aaa96ce2c3d3f7db1 | 39.403846 | 159 | 0.714422 | 4.168651 | false | false | false | false |
hectorrios/TaskIt | TaskIt/ViewController.swift | 1 | 2600 | //
// ViewController.swift
// TaskIt
//
// Created by Hector Rios on 29/06/15.
// Copyright (c) 2015 HectorRios. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var taskArray : [TaskModel] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let task1 = TaskModel(task: "Study French", subtask: "Verbs", date: "01/10/2014")
let task2: TaskModel = TaskModel(task: "Eat dinner", subtask: "Burgers", date: "14/01/2015")
let task3: TaskModel = TaskModel(task: "Gym", subtask: "Leg Day", date: "14/01/2015")
self.taskArray = [task1, task2, task3]
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "showTaskDetail") {
let detailVC: TaskDetailViewController = segue.destinationViewController as! TaskDetailViewController
//returns an Optional which we'll need to unwrap later on
let indexPath = self.tableView.indexPathForSelectedRow()
let thisTask: TaskModel = self.taskArray[indexPath!.row]
detailVC.detailTaskModel = thisTask
}
}
// MARK: UITableViewDataSource protocol methods
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
println(indexPath.row)
var cell : TaskCell = tableView.dequeueReusableCellWithIdentifier("myCell") as! TaskCell
let thisTask:TaskModel = self.taskArray[indexPath.row]
cell.taskLabel.text = thisTask.task
cell.descriptionLabel.text = thisTask.subtask
cell.dateLabel.text = thisTask.date
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.taskArray.count
}
// MARK: UITableViewDelegate methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println(indexPath.row)
performSegueWithIdentifier("showTaskDetail", sender: self)
}
}
| mit | 1cc9b40d1c2140d6c5123ef83f941aa1 | 30.707317 | 113 | 0.636923 | 5.108055 | false | false | false | false |
CSullivan102/LearnApp | LearnKit/Models/LearnItem.swift | 1 | 2056 | //
// LearnItem.swift
// Learn
//
// Created by Christopher Sullivan on 8/18/15.
// Copyright © 2015 Christopher Sullivan. All rights reserved.
//
import Foundation
import CoreData
public final class LearnItem: ManagedObject {
@NSManaged public var title: String
@NSManaged public var url: NSURL?
@NSManaged public var read: Bool
@NSManaged public var topic: Topic?
@NSManaged public var dateAdded: NSDate
@NSManaged private var type: Int16
@NSManaged public var excerpt: String?
@NSManaged public var wordCount: NSNumber?
@NSManaged public var imageURL: NSURL?
@NSManaged public var pocketItemID: NSNumber?
public var itemType: LearnItemType {
get {
guard let t = LearnItemType(rawValue: type) else {
fatalError("Unknown item type")
}
return t
}
set {
type = newValue.rawValue
}
}
public func copyDataFromPocketItem(pocketItem: PocketItem) {
// Only overwrite title, URL if they're the default value
if let resolvedTitle = pocketItem.resolved_title where title == "" {
title = resolvedTitle
}
if let givenUrl = pocketItem.given_url where url == nil {
url = NSURL(string: givenUrl)
}
excerpt = pocketItem.excerpt
if let itemID = Int32(pocketItem.item_id) {
pocketItemID = NSNumber(int: itemID)
}
if let images = pocketItem.images,
(_, firstImage) = images.first {
imageURL = NSURL(string: firstImage.src)
}
if let wordCount = pocketItem.word_count, wordCountInt = Int32(wordCount) {
self.wordCount = NSNumber(int: wordCountInt)
}
}
}
extension LearnItem: ManagedObjectType {
public static var entityName: String {
return "LearnItem"
}
public static var defaultSortDescriptors: [NSSortDescriptor] {
return [NSSortDescriptor(key: "dateAdded", ascending: false)]
}
} | mit | 147b9b1c15f2203305eb3d21e46ce5f7 | 29.235294 | 83 | 0.619465 | 4.659864 | false | false | false | false |
lucianomarisi/LoadIt | LoadItExample/Models/CitiesResource.swift | 1 | 803 | //
// CitiesResource.swift
// LoadIt
//
// Created by Luciano Marisi on 25/06/2016.
// Copyright © 2016 Luciano Marisi. All rights reserved.
//
import Foundation
import LoadIt
private let baseURL = NSURL(string: "http://localhost:8000/")!
struct CitiesResource: NetworkJSONResourceType, DiskJSONResourceType {
typealias Model = [City]
let url: NSURL
let filename: String
init(continent: String) {
url = baseURL.URLByAppendingPathComponent("\(continent).json")
filename = continent
}
//MARK: JSONResource
func modelFrom(jsonDictionary jsonDictionary: [String: AnyObject]) -> [City]? {
guard let
citiesJSONArray = jsonDictionary["cities"] as? [[String: AnyObject]]
else {
return []
}
return citiesJSONArray.flatMap(City.init)
}
} | mit | 912768cd9e1b4c8e44da3b029cc9a81c | 21.942857 | 81 | 0.685786 | 4.15544 | false | false | false | false |
JGiola/swift-package-manager | Sources/TestSupport/MockDependencyGraph.swift | 1 | 7229 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import Basic
import PackageLoading
import PackageModel
import PackageGraph
import SourceControl
import Utility
/// Represents a mock package.
public struct MockPackage {
/// The name of the package.
public let name: String
/// The current available version of the package.
public let version: Utility.Version?
/// The dependencies of the package.
public let dependencies: [MockDependency]
public init(_ name: String, version: Utility.Version?, dependencies: [MockDependency] = []) {
self.name = name
self.version = version
self.dependencies = dependencies
}
}
/// Represents a mock package dependency.
public struct MockDependency {
/// The name of the dependency.
public let name: String
/// The allowed version range of this dependency.
public let version: Range<Utility.Version>
public init(_ name: String, version: Range<Utility.Version>) {
self.name = name
self.version = version
}
public init(_ name: String, version: Utility.Version) {
self.name = name
self.version = version..<Version(version.major, version.minor, version.patch + 1)
}
}
/// A mock manifest graph creator. It takes in a path where it creates empty repositories for mock packages.
/// For each mock package, it creates a manifest and maps it to the url and that version in mock manifest loader.
/// It provides basic functionality of getting the repo paths and manifests which can be later modified in tests.
public struct MockManifestGraph {
/// The map of repositories created by this class where the key is name of the package.
public let repos: [String: RepositorySpecifier]
/// The generated mock manifest loader.
public let manifestLoader: MockManifestLoader
/// The generated root manifest.
public let rootManifest: Manifest
/// The map of external manifests created.
public let manifests: [MockManifestLoader.Key: Manifest]
/// Present if file system used is in inmemory.
public let repoProvider: InMemoryGitRepositoryProvider?
/// Convinience accessor for repository specifiers.
public func repo(_ package: String) -> RepositorySpecifier {
return repos[package]!
}
/// Convinience accessor for external manifests.
public func manifest(_ package: String, version: Utility.Version) -> Manifest {
return manifests[MockManifestLoader.Key(url: repo(package).url, version: version)]!
}
/// Create instance with mocking on in memory file system.
public init(
at path: AbsolutePath,
rootDeps: [MockDependency],
packages: [MockPackage],
fs: InMemoryFileSystem
) throws {
try self.init(at: path, rootDeps: rootDeps, packages: packages, inMemory: (fs, InMemoryGitRepositoryProvider()))
}
public init(
at path: AbsolutePath,
rootDeps: [MockDependency],
packages: [MockPackage],
inMemory: (fs: InMemoryFileSystem, provider: InMemoryGitRepositoryProvider)? = nil
) throws {
repoProvider = inMemory?.provider
// Create the test repositories, we don't need them to have actual
// contents (the manifests are mocked).
let repos = Dictionary(items: try packages.map({ package -> (String, RepositorySpecifier) in
let repoPath = path.appending(component: package.name)
let tag = package.version?.description ?? "initial"
let specifier = RepositorySpecifier(url: repoPath.asString)
// If this is in memory mocked graph.
if let inMemory = inMemory {
if !inMemory.fs.exists(repoPath) {
let repo = InMemoryGitRepository(path: repoPath, fs: inMemory.fs)
try repo.createDirectory(repoPath, recursive: true)
let filePath = repoPath.appending(component: "source.swift")
try repo.writeFileContents(filePath, bytes: "foo")
repo.commit()
try repo.tag(name: tag)
inMemory.provider.add(specifier: specifier, repository: repo)
}
} else {
// Don't recreate repo if it is already there.
if !exists(repoPath) {
try makeDirectories(repoPath)
initGitRepo(repoPath, tag: package.version?.description ?? "initial")
}
}
return (package.name, specifier)
}))
let src = path.appending(component: "Sources")
if let fs = inMemory?.fs {
try fs.createDirectory(src, recursive: true)
try fs.writeFileContents(src.appending(component: "foo.swift"), bytes: "")
} else {
// Make a sources folder for our root package.
try makeDirectories(src)
try systemQuietly(["touch", src.appending(component: "foo.swift").asString])
}
// Create the root manifest.
rootManifest = Manifest(
name: "Root",
platforms: [],
path: path.appending(component: Manifest.filename),
url: path.asString,
version: nil,
manifestVersion: .v4,
dependencies: MockManifestGraph.createDependencies(repos: repos, dependencies: rootDeps)
)
// Create the manifests from mock packages.
var manifests = Dictionary(items: packages.map({ package -> (MockManifestLoader.Key, Manifest) in
let url = repos[package.name]!.url
let manifest = Manifest(
name: package.name,
platforms: [],
path: AbsolutePath(url).appending(component: Manifest.filename),
url: url,
version: package.version,
manifestVersion: .v4,
dependencies: MockManifestGraph.createDependencies(repos: repos, dependencies: package.dependencies)
)
return (MockManifestLoader.Key(url: url, version: package.version), manifest)
}))
// Add the root manifest.
manifests[MockManifestLoader.Key(url: path.asString, version: nil)] = rootManifest
manifestLoader = MockManifestLoader(manifests: manifests)
self.manifests = manifests
self.repos = repos
}
/// Maps MockDependencies into PackageDescription's Dependency array.
private static func createDependencies(
repos: [String: RepositorySpecifier],
dependencies: [MockDependency]
) -> [PackageDependencyDescription] {
return dependencies.map({ dependency in
return PackageDependencyDescription(
url: repos[dependency.name]?.url ?? "//\(dependency.name)",
requirement: .range(dependency.version.lowerBound ..< dependency.version.upperBound))
})
}
}
| apache-2.0 | 4a754e7b286053726b7b9542d0b1ea3c | 38.075676 | 120 | 0.640753 | 4.937842 | false | false | false | false |
gerardogrisolini/iWebretail | iWebretail/MovementsController.swift | 1 | 6583 | //
// MovementsController.swift
// iWebretail
//
// Created by Gerardo Grisolini on 14/04/17.
// Copyright © 2017 Gerardo Grisolini. All rights reserved.
//
import UIKit
import CoreData
class ProgressNotification {
var current: Int = 0
var total: Int = 0
}
class MovementsController: UITableViewController {
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var datePickerButton: UIBarButtonItem!
var datePickerView: UIDatePicker!
var filtered = [(key:String, value:[Movement])]()
private let repository: MovementProtocol
required init?(coder aDecoder: NSCoder) {
repository = IoCContainer.shared.resolve() as MovementProtocol
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
datePickerView = UIDatePicker()
datePickerView.backgroundColor = UIColor.init(name: "lightgray")
datePickerView.datePickerMode = UIDatePickerMode.date
datePickerView.timeZone = TimeZone(abbreviation: "UTC")
datePickerView.addTarget(self, action: #selector(datePickerValueChanged), for: .valueChanged)
self.refreshControl?.addTarget(self, action: #selector(synchronize), for: UIControlEvents.valueChanged)
}
override func viewDidAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveNotification(notification:)), name: NSNotification.Name(rawValue: kProgressUpdateNotification), object: nil)
if datePickerButton?.title != "Date".locale {
refreshData(date: datePickerButton.title?.toDateShort())
} else {
refreshData(date: nil)
}
}
override func viewDidDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(NSNotification.Name(rawValue: kProgressUpdateNotification))
}
@objc func synchronize(sender:AnyObject)
{
//TODO: make this awaitable
DispatchQueue.global(qos: .background).async {
Synchronizer.shared.syncronize()
DispatchQueue.main.async {
self.datePickerButton.title = "Date".locale
self.refreshData(date: nil)
self.refreshControl?.endRefreshing()
}
}
self.refreshControl?.endRefreshing()
}
func refreshData(date: Date?) {
do {
filtered = try repository.getAllGrouped(date: date)
self.tableView.reloadData()
} catch {
self.navigationController?.alert(title: "Error".locale, message: "\(error)")
}
}
@IBAction func dateChange(_ sender: UIBarButtonItem) {
if datePickerButton.title == "Cancel".locale {
datePickerButton.title = "Date".locale
refreshData(date: nil)
datePickerView.removeFromSuperview()
} else if datePickerButton.title == "Done".locale {
datePickerButton.title = datePickerView.date.formatDateShort()
refreshData(date: datePickerView.date)
datePickerView.removeFromSuperview()
} else {
datePickerButton.title = "Cancel".locale
datePickerView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 200)
self.view.addSubview(datePickerView)
}
}
@objc func datePickerValueChanged(sender: UIDatePicker) {
datePickerButton.title = "Done".locale
}
@objc func didReceiveNotification(notification:NSNotification) {
if let progress = notification.object as? ProgressNotification {
if progress.current == progress.total {
DispatchQueue.main.async {
self.progressView.setProgress(1.0, animated: false)
self.progressView.setProgress(0.0, animated: false)
}
} else {
let perc = Float(progress.current) / Float(progress.total)
DispatchQueue.main.async {
self.progressView.setProgress(perc, animated: false)
}
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return self.filtered.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return filtered[section].key
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filtered[section].value.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MovementCell", for: indexPath)
let movement = filtered[indexPath.section].value[indexPath.row]
if movement.synced {
cell.imageView?.image = UIImage.init(named: "sync")
} else if movement.completed {
cell.imageView?.image = UIImage.init(named: "tosync")
} else {
cell.imageView?.image = UIImage.init(named: "build")
}
cell.textLabel?.text = "\(movement.movementCausal?.getJSONValues()["causalName"] ?? "New".locale) n° \(movement.movementNumber)"
if let name = movement.movementRegistry?.getJSONValues()["registryName"] {
cell.detailTextLabel?.text = "\(movement.movementAmount.formatCurrency()) - \(name)s"
} else {
cell.detailTextLabel?.text = movement.movementAmount.formatCurrency()
}
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
do {
try repository.delete(id: filtered[indexPath.section].value[indexPath.row].movementId)
self.filtered[indexPath.section].value.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} catch {
self.navigationController?.alert(title: "Error".locale, message: "\(error)")
}
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.destination is UITabBarController {
let tabViewController: UITabBarController = segue.destination as! UITabBarController
let indexPath = self.tableView?.indexPathForSelectedRow
if (indexPath == nil) {
do {
Synchronizer.shared.movement = try repository.add()
} catch {
self.navigationController?.alert(title: "Error".locale, message: "\(error)")
}
} else {
Synchronizer.shared.movement = filtered[indexPath!.section].value[indexPath!.row]
}
tabViewController.navigationItem.title = String(Synchronizer.shared.movement.movementNumber)
}
}
}
| apache-2.0 | ab22de52151c2f84adc11ad8aab7a4b0 | 33.098446 | 191 | 0.690017 | 4.38441 | false | false | false | false |
KYawn/myiOS | TakePhotos/TakePhotos/ViewController.swift | 1 | 4637 | //
// ViewController.swift
// Taking Photos with the Camera
//
// Created by Vandad Nahavandipoor on 7/10/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at [email protected]
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
import UIKit
import MobileCoreServices
class ViewController: UIViewController,
UINavigationControllerDelegate, UIImagePickerControllerDelegate {
/* We will use this variable to determine if the viewDidAppear:
method of our view controller is already called or not. If not, we will
display the camera view */
var beenHereBefore = false
var controller: UIImagePickerController?
func imagePickerController(picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){
println("Picker returned successfully")
let mediaType:AnyObject? = info[UIImagePickerControllerMediaType]
if let type:AnyObject = mediaType{
if type is String{
let stringType = type as? String
if stringType == kUTTypeMovie{
let urlOfVideo = info[UIImagePickerControllerMediaURL] as? NSURL
if let url = urlOfVideo{
println("Video URL = \(url)")
}
}
else if stringType == kUTTypeImage {
/* Let's get the metadata. This is only for images. Not videos */
let metadata = info[UIImagePickerControllerMediaMetadata]
as? NSDictionary
if let theMetaData = metadata{
let image = info[UIImagePickerControllerOriginalImage]
as? UIImage
if let theImage = image{
println("Image Metadata = \(theMetaData)")
println("Image = \(theImage)")
}
}
}
}
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
println("Picker was cancelled")
picker.dismissViewControllerAnimated(true, completion: nil)
}
func isCameraAvailable() -> Bool{
return UIImagePickerController.isSourceTypeAvailable(.Camera)
}
func cameraSupportsMedia(mediaType: String,
sourceType: UIImagePickerControllerSourceType) -> Bool{
return true
}
func doesCameraSupportTakingPhotos() -> Bool{
return cameraSupportsMedia(kUTTypeImage , sourceType: .Camera)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if beenHereBefore{
/* Only display the picker once as the viewDidAppear: method gets
called whenever the view of our view controller gets displayed */
return;
} else {
beenHereBefore = true
}
if isCameraAvailable() && doesCameraSupportTakingPhotos(){
controller = UIImagePickerController()
if let theController = controller{
theController.sourceType = .Camera
theController.mediaTypes = [kUTTypeImage]
theController.allowsEditing = true
theController.delegate = self
presentViewController(theController, animated: true, completion: nil)
}
} else {
println("Camera is not available")
}
}
}
| apache-2.0 | 0f595bdc833d2a819036b46c239c1c4c | 35.801587 | 89 | 0.573431 | 5.975515 | false | false | false | false |
tassiahmed/SplitScreen | OSX/SplitScreen/File.swift | 1 | 4467 | //
// File.swift
// SplitScreen
//
// Created by Tausif Ahmed on 4/26/16.
// Copyright © 2016 SplitScreen. All rights reserved.
//
import Foundation
import AppKit
class File: Equatable {
fileprivate var path: URL
fileprivate var file_name: String
/**
Inits the `File` with the `dirPath` and `name`
- Parameter dirPath: `NSURL` that is where the file will be located
- Parameter name: `String` that to the name of the `File`
*/
init(dirPath: URL, name: String) {
file_name = name
path = dirPath.appendingPathComponent(name)
}
/**
Returns `file_name`
- Returns: `String` that is the name of the `File`
*/
func getFileName() -> String {
return file_name
}
/**
Returns `path`
- Returns: `String` representation of the `NSURL` for the `File`
*/
func getPathString() -> String {
return path.path
}
/**
Parses the contents of a file from a text file to an `array` of `arrays` of `Int` values
- Parameter height: `Int` that corresponds to screen's height
- Parameter width: `Int` that corresponds to screen's width
- Returns: `array` of `arrays` of `Int` that contains values for a `SnapPoint` for each `array`
*/
func parseFileContent(_ height: Int, width: Int) -> [[Int]] {
var text: String = String()
var snap_params: [[Int]] = []
// Attempt to get text from file
do {
try text = String(contentsOfFile: path.path, encoding: String.Encoding.utf8)
} catch _ {
print("Could not read from \(file_name)")
}
// Split the text into lines
let lines = text.split(separator: "\n").map(String.init)
for line in lines {
// Split line into the different values of a SnapPoint
let components = line.split(separator: ",").map(String.init)
var snap_param: [Int] = []
for component in components {
// General values
if component == "HEIGHT" {
snap_param.append(height)
} else if component == "WIDTH" {
snap_param.append(width)
} else if component == "0" {
snap_param.append(0)
} else if component != components.last {
if component.range(of: "/") != nil {
let dividends = component.split(separator: "/").map(String.init)
if dividends[0] == "HEIGHT" {
snap_param.append(height/Int(dividends[1])!)
} else {
snap_param.append(width/Int(dividends[1])!)
}
} else if component.range(of: "-") != nil {
let dividends = component.split(separator: "-").map(String.init)
if dividends[0] == "HEIGHT" {
snap_param.append(height - Int(dividends[1])!)
} else {
snap_param.append(width - Int(dividends[1])!)
}
}
// For the snap points that are stored as pairs
} else {
let snap_points = component.split(separator: ":").map(String.init)
for snap_point in snap_points {
var xCoord: Int
var yCoord: Int
var tuple: String = snap_point
tuple.remove(at: tuple.startIndex)
tuple.remove(at: tuple.index(before: tuple.endIndex))
let coords = tuple.split(separator: ";").map(String.init)
if coords[0] == "0" {
xCoord = 0
} else if coords[0].range(of: "-") != nil {
let dividends = coords[0].split(separator: "-").map(String.init)
xCoord = width - Int(dividends[1])!
} else if coords[0].range(of: "/") != nil {
let dividends = coords[0].split(separator: "/").map(String.init)
xCoord = width/Int(dividends[1])!
} else {
xCoord = width
}
if coords[1] == "0" {
yCoord = 0
} else if coords[1].range(of: "-") != nil {
let dividends = coords[1].split(separator: "-").map(String.init)
yCoord = height - Int(dividends[1])!
} else if coords[1].range(of: "/") != nil {
let dividends = coords[1].split(separator: "/").map(String.init)
yCoord = height/Int(dividends[1])!
} else {
yCoord = height
}
snap_param.append(xCoord)
snap_param.append(yCoord)
}
}
}
snap_params.append(snap_param)
}
return snap_params
}
}
/**
Creates an equality function for files based on their `path` and `file_name`
- Parameter lhs: `File` that is the left hand `File`
- Parameter rhs: `File` that is the right hand `File`
- Returns: `Bool` that teels whether or not the 2 `File` objects are the same
*/
func ==(lhs: File, rhs: File) -> Bool {
return lhs.getPathString() == rhs.getPathString() && lhs.getFileName() == rhs.getFileName()
}
| apache-2.0 | 44d7d96972dbce29d9f12573c2c6bc5d | 27.628205 | 97 | 0.611509 | 3.26462 | false | false | false | false |
The-iPocalypse/BA-iOS-Application | src/GoodDeed.swift | 1 | 2172 | //
// GoodDeed.swift
// BA-iOS-Application
//
// Created by Vincent Dupuis on 2016-02-12.
// Copyright © 2016 Samuel Bellerose. All rights reserved.
//
import Foundation
import SwiftyJSON
import MapKit
import CoreLocation
class GoodDeed: NSObject, MKAnnotation {
var id: Int
var title: String?
var desc: String
var address: String
var startDate: NSDate
var endDate: NSDate
var creator: User
var long: Double
var lat: Double
let locationName: String
let coordinate: CLLocationCoordinate2D
var distance: Double
init(json: JSON) {
self.id = json["id"].intValue
self.title = json["title"].string!
self.desc = json["description"].string!
self.address = json["address"].string!
self.startDate = DateHelper.instance.dateFromString(json["start_at"].string!)!
self.endDate = DateHelper.instance.dateFromString(json["end_at"].string!)!
self.creator = User(json: json["creator"])
self.long = json["longitude"].doubleValue
self.lat = json["latitude"].doubleValue
self.coordinate = CLLocationCoordinate2D(latitude: self.lat, longitude: self.long)
self.locationName = self.desc
self.distance = 0
}
init(id: Int, title: String, description: String, address: String, startDate: NSDate, endDate: NSDate, creator: User, long: Double, lat: Double) {
self.id = id
self.title = title
self.desc = description
self.address = address
self.startDate = startDate
self.endDate = endDate
self.creator = creator
self.long = long
self.lat = lat
self.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
self.locationName = self.desc
self.distance = 0
}
var subtitle: String? {
return locationName
}
func getDistanceFromUser(source:CLLocation) -> Double {
let destination = CLLocation(latitude: lat, longitude: long)
let distanceMeters = source.distanceFromLocation(destination)
self.distance = (distanceMeters / 1000)
return self.distance
}
}
| mit | bc8c60ce8a2873e0560b742cb5af8945 | 30.463768 | 150 | 0.645785 | 4.430612 | false | false | false | false |
ivanasmiljic/test | Example/Segmentio/ViewControllers/ExampleViewController.swift | 1 | 5273 | //
// ExampleViewController.swift
// Segmentio
//
// Created by Dmitriy Demchenko
// Copyright © 2016 Yalantis Mobile. All rights reserved.
//
import UIKit
import Segmentio
class ExampleViewController: UIViewController {
var segmentioStyle = SegmentioStyle.imageOverLabel
@IBOutlet fileprivate weak var segmentViewHeightConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var segmentioView: Segmentio!
@IBOutlet fileprivate weak var containerView: UIView!
@IBOutlet fileprivate weak var scrollView: UIScrollView!
fileprivate lazy var viewControllers: [UIViewController] = {
return self.preparedViewControllers()
}()
// MARK: - Init
class func create() -> ExampleViewController {
let board = UIStoryboard(name: "Main", bundle: nil)
return board.instantiateViewController(withIdentifier: String(describing: self)) as! ExampleViewController
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
switch segmentioStyle {
case .onlyLabel, .imageBeforeLabel, .imageAfterLabel:
segmentViewHeightConstraint.constant = 50
case .onlyImage:
segmentViewHeightConstraint.constant = 100
default:
break
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setupScrollView()
SegmentioBuilder.buildSegmentioView(
segmentioView: segmentioView,
segmentioStyle: segmentioStyle
)
SegmentioBuilder.setupBadgeCountForIndex(segmentioView, index: 1)
segmentioView.selectedSegmentioIndex = selectedSegmentioIndex()
segmentioView.valueDidChange = { [weak self] _, segmentIndex in
if let scrollViewWidth = self?.scrollView.frame.width {
let contentOffsetX = scrollViewWidth * CGFloat(segmentIndex)
self?.scrollView.setContentOffset(
CGPoint(x: contentOffsetX, y: 0),
animated: true
)
}
}
}
// Example viewControllers
fileprivate func preparedViewControllers() -> [ContentViewController] {
let tornadoController = ContentViewController.create()
tornadoController.disaster = Disaster(
cardName: "Before tornado",
hints: Hints.tornado
)
let earthquakesController = ContentViewController.create()
earthquakesController.disaster = Disaster(
cardName: "Before earthquakes",
hints: Hints.earthquakes
)
let extremeHeatController = ContentViewController.create()
extremeHeatController.disaster = Disaster(
cardName: "Before extreme heat",
hints: Hints.extremeHeat
)
let eruptionController = ContentViewController.create()
eruptionController.disaster = Disaster(
cardName: "Before eruption",
hints: Hints.eruption
)
let floodsController = ContentViewController.create()
floodsController.disaster = Disaster(
cardName: "Before floods",
hints: Hints.floods
)
let wildfiresController = ContentViewController.create()
wildfiresController.disaster = Disaster(
cardName: "Before wildfires",
hints: Hints.wildfires
)
return [
tornadoController,
earthquakesController,
extremeHeatController,
eruptionController,
floodsController,
wildfiresController
]
}
fileprivate func selectedSegmentioIndex() -> Int {
return 0
}
// MARK: - Setup container view
fileprivate func setupScrollView() {
scrollView.contentSize = CGSize(
width: UIScreen.main.bounds.width * CGFloat(viewControllers.count),
height: containerView.frame.height
)
for (index, viewController) in viewControllers.enumerated() {
viewController.view.frame = CGRect(
x: UIScreen.main.bounds.width * CGFloat(index),
y: 0,
width: scrollView.frame.width,
height: scrollView.frame.height
)
addChildViewController(viewController)
scrollView.addSubview(viewController.view, options: .useAutoresize) // module's extension
viewController.didMove(toParentViewController: self)
}
}
// MARK: - Actions
fileprivate func goToControllerAtIndex(_ index: Int) {
segmentioView.selectedSegmentioIndex = index
}
}
extension ExampleViewController: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let currentPage = floor(scrollView.contentOffset.x / scrollView.frame.width)
segmentioView.selectedSegmentioIndex = Int(currentPage)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: 0)
}
}
| mit | 29db7451ac9456a08369a019b3d46a70 | 31.343558 | 114 | 0.62519 | 5.572939 | false | false | false | false |
wayfinders/WRCalendarView | WRCalendarView/FlowLayout/WRWeekViewFlowLayout.swift | 1 | 35772 | //
// WRWeekViewFlowLayout.swift
// Pods
//
// Created by wayfinder on 2017. 4. 26..
//
//
import UIKit
import DateToolsSwift
protocol WRWeekViewFlowLayoutDelegate {
func collectionView(_ collectionView: UICollectionView, layout: WRWeekViewFlowLayout, dayForSection section: Int) -> Date
func collectionView(_ collectionView: UICollectionView, layout: WRWeekViewFlowLayout, startTimeForItemAtIndexPath indexPath: IndexPath) -> Date
func collectionView(_ collectionView: UICollectionView, layout: WRWeekViewFlowLayout, endTimeForItemAtIndexPath indexPath: IndexPath) -> Date
}
class WRWeekViewFlowLayout: UICollectionViewFlowLayout {
typealias AttDic = Dictionary<IndexPath, UICollectionViewLayoutAttributes>
// UI params
var hourHeight: CGFloat!
var rowHeaderWidth: CGFloat!
var columnHeaderHeight: CGFloat!
var sectionWidth: CGFloat!
var hourGridDivisionValue: HourGridDivision!
var minuteHeight: CGFloat { return hourHeight / 60 }
let displayHeaderBackgroundAtOrigin = true
let gridThickness: CGFloat = UIScreen.main.scale == 2 ? 0.5 : 1.0
let minOverlayZ = 1000 // Allows for 900 items in a section without z overlap issues
let minCellZ = 100 // Allows for 100 items in a section's background
let minBackgroundZ = 0
var maxSectionHeight: CGFloat { return columnHeaderHeight + hourHeight * 24 }
var currentTimeIndicatorSize: CGSize { return CGSize(width: rowHeaderWidth, height: 10.0) }
let sectionMargin = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
let cellMargin = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
let contentsMargin = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
var delegate: WRWeekViewFlowLayoutDelegate?
var currentTimeComponents: DateComponents {
if (cachedCurrentTimeComponents[0] != nil) {
return cachedCurrentTimeComponents[0]!
}
cachedCurrentTimeComponents[0] = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: Date())
return cachedCurrentTimeComponents[0]!
}
var minuteTimer: Timer?
// Attributes
var cachedDayDateComponents = Dictionary<Int, DateComponents>()
var cachedCurrentTimeComponents = Dictionary<Int, DateComponents>()
var cachedStartTimeDateComponents = Dictionary<IndexPath, DateComponents>()
var cachedEndTimeDateComponents = Dictionary<IndexPath, DateComponents>()
var registeredDecorationClasses = Dictionary<String, AnyClass>()
var needsToPopulateAttributesForAllSections = true
var allAttributes = Array<UICollectionViewLayoutAttributes>()
var itemAttributes = AttDic()
var columnHeaderAttributes = AttDic()
var columnHeaderBackgroundAttributes = AttDic()
var rowHeaderAttributes = AttDic()
var rowHeaderBackgroundAttributes = AttDic()
var verticalGridlineAttributes = AttDic()
var horizontalGridlineAttributes = AttDic()
var todayBackgroundAttributes = AttDic()
var cornerHeaderAttributes = AttDic()
var currentTimeIndicatorAttributes = AttDic()
var currentTimeHorizontalGridlineAttributes = AttDic()
// MARK:- Life cycle
override init() {
super.init()
initialize()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
minuteTimer?.invalidate()
}
func initialize() {
hourHeight = 50
rowHeaderWidth = 50
columnHeaderHeight = 50
hourGridDivisionValue = .minutes_20
initializeMinuteTick()
}
func initializeMinuteTick() {
minuteTimer = Timer(fireAt: Date() + 1.minutes, interval: TimeInterval(60), target: self, selector: #selector(minuteTick), userInfo: nil, repeats: true)
RunLoop.current.add(minuteTimer!, forMode: .defaultRunLoopMode)
}
func minuteTick() {
cachedCurrentTimeComponents.removeAll()
invalidateLayout()
}
// MARK: - UICollectionViewLayout
override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) {
invalidateLayoutCache()
prepare()
super.prepare(forCollectionViewUpdates: updateItems)
}
override func finalizeCollectionViewUpdates() {
for subview in collectionView!.subviews {
for decorationViewClass in registeredDecorationClasses.values {
if subview.isKind(of: decorationViewClass) {
subview.removeFromSuperview()
}
}
}
collectionView!.reloadData()
}
override func register(_ viewClass: AnyClass?, forDecorationViewOfKind elementKind: String) {
super.register(viewClass, forDecorationViewOfKind: elementKind)
registeredDecorationClasses[elementKind] = viewClass
}
override func prepare() {
super.prepare()
if needsToPopulateAttributesForAllSections {
prepareHorizontalTileSectionLayoutForSections(NSIndexSet.init(indexesIn:
NSRange.init(location: 0, length: collectionView!.numberOfSections)))
needsToPopulateAttributesForAllSections = false
}
let needsToPopulateAllAttributes = (allAttributes.count == 0)
if needsToPopulateAllAttributes {
allAttributes.append(contentsOf: columnHeaderAttributes.values)
allAttributes.append(contentsOf: columnHeaderBackgroundAttributes.values)
allAttributes.append(contentsOf: rowHeaderAttributes.values)
allAttributes.append(contentsOf: rowHeaderBackgroundAttributes.values)
allAttributes.append(contentsOf: verticalGridlineAttributes.values)
allAttributes.append(contentsOf: horizontalGridlineAttributes.values)
allAttributes.append(contentsOf: todayBackgroundAttributes.values)
allAttributes.append(contentsOf: cornerHeaderAttributes.values)
allAttributes.append(contentsOf: currentTimeHorizontalGridlineAttributes.values)
allAttributes.append(contentsOf: currentTimeIndicatorAttributes.values)
allAttributes.append(contentsOf: itemAttributes.values)
}
}
func prepareHorizontalTileSectionLayoutForSections(_ sectionIndexes: NSIndexSet) {
guard collectionView!.numberOfSections != 0 else { return }
var attributes = UICollectionViewLayoutAttributes()
let needsToPopulateItemAttributes = (itemAttributes.count == 0)
let needsToPopulateVerticalGridlineAttributes = (verticalGridlineAttributes.count == 0)
let sectionWidth = sectionMargin.left + self.sectionWidth + sectionMargin.right
let sectionHeight = nearbyint(hourHeight * 24 + sectionMargin.top + sectionMargin.bottom)
let calendarGridMinX = rowHeaderWidth + contentsMargin.left
let calendarGridMinY = columnHeaderHeight + contentsMargin.top
let calendarGridWidth = collectionViewContentSize.width - rowHeaderWidth - contentsMargin.left - contentsMargin.right
let calendarContentMinX = rowHeaderWidth + contentsMargin.left + sectionMargin.left
let calendarContentMinY = columnHeaderHeight + contentsMargin.top + sectionMargin.top
// row header
let rowHeaderMinX = fmax(collectionView!.contentOffset.x, 0)
// row Header Background
(attributes, rowHeaderBackgroundAttributes) =
layoutAttributesForDecorationView(at: IndexPath(row: 0, section: 0),
ofKind: DecorationViewKinds.rowHeaderBackground,
withItemCache: rowHeaderBackgroundAttributes)
attributes.frame = CGRect(x: rowHeaderMinX, y: collectionView!.contentOffset.y,
width: rowHeaderWidth, height: collectionView!.frame.height)
attributes.zIndex = zIndexForElementKind(DecorationViewKinds.rowHeaderBackground)
//current time indicator
(attributes, currentTimeIndicatorAttributes) =
layoutAttributesForDecorationView(at: IndexPath(row: 0, section: 0),
ofKind: DecorationViewKinds.currentTimeIndicator,
withItemCache: currentTimeIndicatorAttributes)
let timeY = calendarContentMinX + nearbyint(CGFloat(currentTimeComponents.hour!) * hourHeight
+ CGFloat(currentTimeComponents.minute!) * minuteHeight)
let currentTimeIndicatorMinY: CGFloat = timeY - nearbyint(currentTimeIndicatorSize.height / 2.0)
let currentTimeIndicatorMinX: CGFloat = (max(collectionView!.contentOffset.x, 0.0) + (rowHeaderWidth - currentTimeIndicatorSize.width))
attributes.frame = CGRect(origin: CGPoint(x: currentTimeIndicatorMinX, y: currentTimeIndicatorMinY),
size: currentTimeIndicatorSize)
attributes.zIndex = zIndexForElementKind(DecorationViewKinds.currentTimeIndicator)
//current time gridline
(attributes, currentTimeHorizontalGridlineAttributes) =
layoutAttributesForDecorationView(at: IndexPath(row: 0, section: 0),
ofKind: DecorationViewKinds.currentTimeGridline,
withItemCache: currentTimeHorizontalGridlineAttributes)
let currentTimeHorizontalGridlineMinY = timeY - nearbyint(gridThickness / 2.0)
let currentTimeHorizontalGridlineXOffset = calendarGridMinX + sectionMargin.left
let currentTimeHorizontalGridlineMinX = max(currentTimeHorizontalGridlineXOffset, collectionView!.contentOffset.x + currentTimeHorizontalGridlineXOffset)
let currentTimehorizontalGridlineWidth = min(calendarGridWidth, collectionView!.frame.size.width)
attributes.frame = CGRect(x: currentTimeHorizontalGridlineMinX, y: currentTimeHorizontalGridlineMinY,
width: currentTimehorizontalGridlineWidth, height: gridThickness);
attributes.zIndex = zIndexForElementKind(DecorationViewKinds.currentTimeGridline)
// column header background
(attributes, columnHeaderBackgroundAttributes) =
layoutAttributesForDecorationView(at: IndexPath(row: 0, section: 0),
ofKind: DecorationViewKinds.columnHeaderBackground,
withItemCache: columnHeaderBackgroundAttributes)
attributes.frame = CGRect(origin: collectionView!.contentOffset,
size: CGSize(width: collectionView!.frame.width,
height: columnHeaderHeight + (collectionView!.contentOffset.y < 0 ? abs(collectionView!.contentOffset.y) : 0 )))
attributes.zIndex = zIndexForElementKind(DecorationViewKinds.columnHeaderBackground)
// corner
(attributes, cornerHeaderAttributes) =
layoutAttributesForDecorationView(at: IndexPath(row: 0, section: 0),
ofKind: DecorationViewKinds.cornerHeader,
withItemCache: cornerHeaderAttributes)
attributes.frame = CGRect(origin: collectionView!.contentOffset,
size: CGSize.init(width: rowHeaderWidth, height: columnHeaderHeight))
attributes.zIndex = zIndexForElementKind(DecorationViewKinds.cornerHeader)
// row header
for rowHeaderIndex in 0...23 {
(attributes, rowHeaderAttributes) =
layoutAttributesForSupplemantaryView(at: IndexPath(item: rowHeaderIndex, section: 0),
ofKind: SupplementaryViewKinds.rowHeader,
withItemCache: rowHeaderAttributes)
let rowHeaderMinY = calendarContentMinY + hourHeight * CGFloat(rowHeaderIndex) - nearbyint(hourHeight / 2.0)
attributes.frame = CGRect(x: rowHeaderMinX,
y: rowHeaderMinY,
width: rowHeaderWidth,
height: hourHeight)
attributes.zIndex = zIndexForElementKind(SupplementaryViewKinds.rowHeader)
}
// Column Header
let columnHeaderMinY = fmax(collectionView!.contentOffset.y, 0.0)
sectionIndexes.enumerate(_:) { (section, stop) in
let sectionMinX = calendarContentMinX + sectionWidth * CGFloat(section)
(attributes, columnHeaderAttributes) =
layoutAttributesForSupplemantaryView(at: IndexPath(item: 0, section: section),
ofKind: SupplementaryViewKinds.columnHeader,
withItemCache: columnHeaderAttributes)
attributes.frame = CGRect(x: sectionMinX, y: columnHeaderMinY,
width: sectionWidth, height: columnHeaderHeight)
attributes.zIndex = zIndexForElementKind(SupplementaryViewKinds.columnHeader)
if needsToPopulateVerticalGridlineAttributes {
layoutVerticalGridLinesAttributes(section: section, sectionX: sectionMinX, calendarGridMinY: calendarGridMinY, sectionHeight: sectionHeight)
layoutTodayBackgroundAttributes(section: section, sectionX: sectionMinX, calendarStartY: calendarGridMinY, sectionHeight: sectionHeight)
}
if needsToPopulateItemAttributes {
layoutItemsAttributes(section: section, sectionX: sectionMinX, calendarStartY: calendarGridMinY)
}
}
layoutHorizontalGridLinesAttributes(calendarStartX: calendarContentMinX, calendarStartY: calendarContentMinY)
}
// MARK: - Layout Attributes
func layoutItemsAttributes(section: Int, sectionX: CGFloat, calendarStartY: CGFloat) {
var attributes = UICollectionViewLayoutAttributes()
var sectionItemAttributes = [UICollectionViewLayoutAttributes]()
for item in 0..<collectionView!.numberOfItems(inSection: section) {
let itemIndexPath = IndexPath(item: item, section: section)
(attributes, itemAttributes) =
layoutAttributesForCell(at: itemIndexPath, withItemCache: itemAttributes)
let itemStartTime = startTimeForIndexPath(itemIndexPath)
let itemEndTime = endTimeForIndexPath(itemIndexPath)
let startHourY = CGFloat(itemStartTime.hour!) * hourHeight
let startMinuteY = CGFloat(itemStartTime.minute!) * minuteHeight
var endHourY: CGFloat
let endMinuteY = CGFloat(itemEndTime.minute!) * minuteHeight
if itemEndTime.day! != itemStartTime.day! {
endHourY = CGFloat(Calendar.current.maximumRange(of: .hour)!.count) * hourHeight + CGFloat(itemEndTime.hour!) * hourHeight
} else {
endHourY = CGFloat(itemEndTime.hour!) * hourHeight
}
let itemMinX = nearbyint(sectionX + cellMargin.left)
let itemMinY = nearbyint(startHourY + startMinuteY + calendarStartY + cellMargin.top)
let itemMaxX = nearbyint(itemMinX + (sectionWidth - (cellMargin.left + cellMargin.right)))
let itemMaxY = nearbyint(endHourY + endMinuteY + calendarStartY - cellMargin.bottom)
attributes.frame = CGRect(x: itemMinX, y: itemMinY,
width: itemMaxX - itemMinX,
height: itemMaxY - itemMinY)
attributes.zIndex = zIndexForElementKind(SupplementaryViewKinds.defaultCell)
sectionItemAttributes.append(attributes)
}
adjustItemsForOverlap(sectionItemAttributes, inSection: section, sectionMinX: sectionX)
}
func layoutTodayBackgroundAttributes(section: Int, sectionX: CGFloat, calendarStartY: CGFloat, sectionHeight: CGFloat) {
let currentComponents = daysForSection(section)
if (currentTimeComponents.year == currentComponents.year &&
currentTimeComponents.month == currentComponents.month &&
currentTimeComponents.day == currentComponents.day) {
var attributes: UICollectionViewLayoutAttributes
(attributes, todayBackgroundAttributes) =
layoutAttributesForDecorationView(at: IndexPath(item: 0, section: 0),
ofKind: DecorationViewKinds.todayBackground,
withItemCache: todayBackgroundAttributes)
attributes.frame = CGRect(x: sectionX, y: 0, width: sectionWidth, height: sectionHeight + calendarStartY)
attributes.zIndex = zIndexForElementKind(DecorationViewKinds.todayBackground)
}
}
func layoutVerticalGridLinesAttributes(section: Int, sectionX: CGFloat, calendarGridMinY: CGFloat, sectionHeight: CGFloat) {
var attributes = UICollectionViewLayoutAttributes()
(attributes, verticalGridlineAttributes) =
layoutAttributesForDecorationView(at: IndexPath(item: 0, section: section),
ofKind: DecorationViewKinds.verticalGridline,
withItemCache: verticalGridlineAttributes)
attributes.frame = CGRect(x: nearbyint(sectionX - gridThickness / 2.0),
y: calendarGridMinY,
width: gridThickness,
height: sectionHeight)
attributes.zIndex = zIndexForElementKind(DecorationViewKinds.verticalGridline)
}
func layoutHorizontalGridLinesAttributes(calendarStartX: CGFloat, calendarStartY: CGFloat) {
var horizontalGridlineIndex = 0
let calendarGridWidth = collectionViewContentSize.width - rowHeaderWidth - contentsMargin.left - contentsMargin.right
var attributes = UICollectionViewLayoutAttributes()
for hour in 0...23 {
(attributes, horizontalGridlineAttributes) =
layoutAttributesForDecorationView(at: IndexPath(item: horizontalGridlineIndex, section: 0),
ofKind: DecorationViewKinds.horizontalGridline,
withItemCache: horizontalGridlineAttributes)
let horizontalGridlineXOffset = calendarStartX + sectionMargin.left
let horizontalGridlineMinX = fmax(horizontalGridlineXOffset, collectionView!.contentOffset.x + horizontalGridlineXOffset)
let horizontalGridlineMinY = nearbyint(calendarStartY + (hourHeight * CGFloat(hour))) - (gridThickness / 2.0)
let horizontalGridlineWidth = fmin(calendarGridWidth, collectionView!.frame.width)
attributes.frame = CGRect(x: horizontalGridlineMinX,
y: horizontalGridlineMinY,
width: horizontalGridlineWidth,
height: gridThickness)
attributes.zIndex = zIndexForElementKind(DecorationViewKinds.horizontalGridline)
horizontalGridlineIndex += 1
if hourGridDivisionValue.rawValue > 0 {
horizontalGridlineIndex = drawHourDividersAtGridLineIndex(horizontalGridlineIndex, hour: hour,
startX: horizontalGridlineMinX,
startY: horizontalGridlineMinY,
gridlineWidth: horizontalGridlineWidth)
}
}
}
func drawHourDividersAtGridLineIndex(_ gridlineIndex: Int, hour: Int, startX calendarStartX: CGFloat,
startY calendarStartY: CGFloat, gridlineWidth: CGFloat) -> Int {
var _gridlineIndex = gridlineIndex
var attributes = UICollectionViewLayoutAttributes()
let numberOfDivisions = 60 / hourGridDivisionValue.rawValue
let divisionHeight = hourHeight / CGFloat(numberOfDivisions)
for division in 1..<numberOfDivisions {
let horizontalGridlineIndexPath = IndexPath(item: _gridlineIndex, section: 0)
(attributes, horizontalGridlineAttributes) = layoutAttributesForDecorationView(at: horizontalGridlineIndexPath,
ofKind: DecorationViewKinds.horizontalGridline,
withItemCache: horizontalGridlineAttributes)
let horizontalGridlineMinY = nearbyint(calendarStartY + (divisionHeight * CGFloat(division)) - (gridThickness / 2.0))
attributes.frame = CGRect(x: calendarStartX, y: horizontalGridlineMinY, width: gridlineWidth, height: gridThickness)
attributes.alpha = 0.3
attributes.zIndex = zIndexForElementKind(DecorationViewKinds.horizontalGridline)
_gridlineIndex += 1
}
return _gridlineIndex
}
override var collectionViewContentSize: CGSize {
let size = CGSize(width: rowHeaderWidth + sectionWidth * CGFloat(collectionView!.numberOfSections),
height: maxSectionHeight)
return size
}
// MARK: - Layout
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return itemAttributes[indexPath]
}
override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
switch elementKind {
case SupplementaryViewKinds.columnHeader:
return columnHeaderAttributes[indexPath]
case SupplementaryViewKinds.rowHeader:
return rowHeaderAttributes[indexPath]
default:
return nil
}
}
override func layoutAttributesForDecorationView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
switch elementKind {
case DecorationViewKinds.verticalGridline:
return verticalGridlineAttributes[indexPath]
case DecorationViewKinds.horizontalGridline:
return horizontalGridlineAttributes[indexPath]
case DecorationViewKinds.rowHeaderBackground:
return rowHeaderBackgroundAttributes[indexPath]
case DecorationViewKinds.columnHeaderBackground:
return columnHeaderBackgroundAttributes[indexPath]
case DecorationViewKinds.todayBackground:
return todayBackgroundAttributes[indexPath]
case DecorationViewKinds.cornerHeader:
return cornerHeaderAttributes[indexPath]
default:
return nil
}
}
// MARK: - Layout
func layoutAttributesForCell(at indexPath: IndexPath, withItemCache itemCache: AttDic) -> (UICollectionViewLayoutAttributes, AttDic) {
var layoutAttributes = itemCache[indexPath]
if layoutAttributes == nil {
var _itemCache = itemCache
layoutAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
_itemCache[indexPath] = layoutAttributes
return (layoutAttributes!, _itemCache)
} else {
return (layoutAttributes!, itemCache)
}
}
func layoutAttributesForDecorationView(at indexPath: IndexPath,
ofKind kind: String,
withItemCache itemCache: AttDic) -> (UICollectionViewLayoutAttributes, AttDic) {
var layoutAttributes = itemCache[indexPath]
if layoutAttributes == nil {
var _itemCache = itemCache
layoutAttributes = UICollectionViewLayoutAttributes(forDecorationViewOfKind: kind, with: indexPath)
_itemCache[indexPath] = layoutAttributes
return (layoutAttributes!, _itemCache)
} else {
return (layoutAttributes!, itemCache)
}
}
func layoutAttributesForSupplemantaryView(at indexPath: IndexPath,
ofKind kind: String,
withItemCache itemCache: AttDic) -> (UICollectionViewLayoutAttributes, AttDic) {
var layoutAttributes = itemCache[indexPath]
if layoutAttributes == nil {
var _itemCache = itemCache
layoutAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: kind, with: indexPath)
_itemCache[indexPath] = layoutAttributes
return (layoutAttributes!, _itemCache)
} else {
return (layoutAttributes!, itemCache)
}
}
func adjustItemsForOverlap(_ sectionItemAttributes: [UICollectionViewLayoutAttributes], inSection: Int, sectionMinX: CGFloat) {
var adjustedAttributes = Set<UICollectionViewLayoutAttributes>()
var sectionZ = minCellZ
for itemAttributes in sectionItemAttributes {
// If an item's already been adjusted, move on to the next one
if adjustedAttributes.contains(itemAttributes) {
continue
}
// Find the other items that overlap with this item
var overlappingItems = [UICollectionViewLayoutAttributes]()
let itemFrame = itemAttributes.frame
overlappingItems.append(contentsOf: sectionItemAttributes.filter {
if $0 != itemAttributes {
return itemFrame.intersects($0.frame)
} else {
return false
}
})
// If there's items overlapping, we need to adjust them
if overlappingItems.count > 0 {
// Add the item we're adjusting to the overlap set
overlappingItems.insert(itemAttributes, at: 0)
var minY = CGFloat.greatestFiniteMagnitude
var maxY = CGFloat.leastNormalMagnitude
for overlappingItemAttributes in overlappingItems {
if overlappingItemAttributes.frame.minY < minY {
minY = overlappingItemAttributes.frame.minY
}
if overlappingItemAttributes.frame.maxY > maxY {
maxY = overlappingItemAttributes.frame.maxY
}
}
// Determine the number of divisions needed (maximum number of currently overlapping items)
var divisions = 1
for currentY in stride(from: minY, to: maxY, by: 1) {
var numberItemsForCurrentY = 0
for overlappingItemAttributes in overlappingItems {
if currentY >= overlappingItemAttributes.frame.minY &&
currentY < overlappingItemAttributes.frame.maxY {
numberItemsForCurrentY += 1
}
}
if numberItemsForCurrentY > divisions {
divisions = numberItemsForCurrentY
}
}
// Adjust the items to have a width of the section size divided by the number of divisions needed
let divisionWidth = nearbyint(sectionWidth / CGFloat(divisions))
var dividedAttributes = [UICollectionViewLayoutAttributes]()
for divisionAttributes in overlappingItems {
let itemWidth = divisionWidth - cellMargin.left - cellMargin.right
// It it hasn't yet been adjusted, perform adjustment
if !adjustedAttributes.contains(divisionAttributes) {
var divisionAttributesFrame = divisionAttributes.frame
divisionAttributesFrame.origin.x = sectionMinX + cellMargin.left
divisionAttributesFrame.size.width = itemWidth
// Horizontal Layout
var adjustments = 1
for dividedItemAttributes in dividedAttributes {
if dividedItemAttributes.frame.intersects(divisionAttributesFrame) {
divisionAttributesFrame.origin.x = sectionMinX + ((divisionWidth * CGFloat(adjustments)) + cellMargin.left)
adjustments += 1
}
}
// Stacking (lower items stack above higher items, since the title is at the top)
divisionAttributes.zIndex = sectionZ
sectionZ += 1
divisionAttributes.frame = divisionAttributesFrame
dividedAttributes.append(divisionAttributes)
adjustedAttributes.insert(divisionAttributes)
}
}
}
}
}
func invalidateLayoutCache() {
needsToPopulateAttributesForAllSections = true
cachedDayDateComponents.removeAll()
verticalGridlineAttributes.removeAll()
horizontalGridlineAttributes.removeAll()
columnHeaderAttributes.removeAll()
columnHeaderBackgroundAttributes.removeAll()
rowHeaderAttributes.removeAll()
rowHeaderBackgroundAttributes.removeAll()
todayBackgroundAttributes.removeAll()
cornerHeaderAttributes.removeAll()
itemAttributes.removeAll()
allAttributes.removeAll()
}
func invalidateItemsCache() {
itemAttributes.removeAll()
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let visibleSections = NSMutableIndexSet()
NSIndexSet.init(indexesIn: NSRange.init(location: 0, length: collectionView!.numberOfSections))
.enumerate(_:) { (section: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
let sectionRect = rectForSection(section)
if rect.intersects(sectionRect) {
visibleSections.add(section)
}
}
prepareHorizontalTileSectionLayoutForSections(visibleSections)
return allAttributes.filter({ rect.intersects($0.frame) })
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
// MARK: - Section sizing
func rectForSection(_ section: Int) -> CGRect {
return CGRect(x: rowHeaderWidth + sectionWidth * CGFloat(section),
y: 0,
width: sectionWidth,
height: collectionViewContentSize.height)
}
// MARK: - Delegate Wrapper
func daysForSection(_ section: Int) -> DateComponents {
if cachedDayDateComponents[section] != nil {
return cachedDayDateComponents[section]!
}
let day = delegate?.collectionView(collectionView!, layout: self, dayForSection: section)
guard day != nil else { fatalError() }
let startOfDay = Calendar.current.startOfDay(for: day!)
let dayDateComponents = Calendar.current.dateComponents([.year, .month, .day], from: startOfDay)
cachedDayDateComponents[section] = dayDateComponents
return dayDateComponents
}
func startTimeForIndexPath(_ indexPath: IndexPath) -> DateComponents {
if cachedStartTimeDateComponents[indexPath] != nil {
return cachedStartTimeDateComponents[indexPath]!
} else {
if let date = delegate?.collectionView(collectionView!, layout: self, startTimeForItemAtIndexPath: indexPath) {
return Calendar.current.dateComponents([.day, .hour, .minute], from: date)
} else {
fatalError()
}
}
}
func endTimeForIndexPath(_ indexPath: IndexPath) -> DateComponents {
if cachedEndTimeDateComponents[indexPath] != nil {
return cachedEndTimeDateComponents[indexPath]!
} else {
if let date = delegate?.collectionView(collectionView!, layout: self, endTimeForItemAtIndexPath: indexPath) {
return Calendar.current.dateComponents([.day, .hour, .minute], from: date)
} else {
fatalError()
}
}
}
// MARK: - Scroll
func scrollCollectionViewToCurrentTime() {
let y = max(0, min(CGFloat(Date().hour) * hourHeight - collectionView!.frame.height / 2 + columnHeaderHeight,
collectionView!.contentSize.height - collectionView!.frame.height))
//didScroll에서 horizontal, vertical scroll이 동시에 되는 것을 막고 있음
//임시로 처음 current time찾아갈 때만 delegate를 무효화하도록 함
//더 나은 방법 찾을때까지 임시 유지
let tempDelegate = collectionView!.delegate
collectionView!.delegate = nil
self.collectionView!.contentOffset = CGPoint(x: self.collectionView!.contentOffset.x, y: y)
collectionView!.delegate = tempDelegate
}
// MARK: - Dates
func dateForTimeRowHeader(at indexPath: IndexPath) -> Date {
var components = daysForSection(indexPath.section)
components.hour = indexPath.item
return Calendar.current.date(from: components)!
}
func dateForColumnHeader(at indexPath: IndexPath) -> Date {
let day = delegate?.collectionView(collectionView!, layout: self, dayForSection: indexPath.section)
return Calendar.current.startOfDay(for: day!)
}
func hourIndexForDate(_ date: Date) -> Int {
return Calendar.current.component(.hour, from: date)
}
// MARK: - z index
func zIndexForElementKind(_ kind: String) -> Int {
switch kind {
case DecorationViewKinds.currentTimeIndicator:
return minOverlayZ + 10
case DecorationViewKinds.cornerHeader:
return minOverlayZ + 9
case SupplementaryViewKinds.rowHeader:
return minOverlayZ + 8
case DecorationViewKinds.rowHeaderBackground:
return minOverlayZ + 7
case SupplementaryViewKinds.columnHeader:
return minOverlayZ + 6
case DecorationViewKinds.columnHeaderBackground:
return minOverlayZ + 5
case DecorationViewKinds.currentTimeGridline:
return minBackgroundZ + 4
case DecorationViewKinds.horizontalGridline:
return minBackgroundZ + 3
case DecorationViewKinds.verticalGridline:
return minBackgroundZ + 2
case DecorationViewKinds.todayBackground:
return minBackgroundZ
default:
return minCellZ
}
}
}
| mit | 8e5354d9ab6d3c9d3d58e0c622799b19 | 49.11236 | 161 | 0.628672 | 5.843433 | false | false | false | false |
piyushjo/demo-quiz-app | QuizApp/Question3ViewController.swift | 1 | 1875 |
import UIKit
import MobileCenterAnalytics
class Question3ViewController: UIViewController {
@IBOutlet weak var logoImageView: UIImageView!
@IBOutlet weak var answer1Button: UIButton!
@IBOutlet weak var answer2Button: UIButton!
@IBOutlet weak var answer3Button: UIButton!
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var currentScoreLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad();
displayPlayerScore();
// If the user has already played this
//if (UserDefaults.standard.bool(forKey: "Q3Played") == true) {
// disableAllButtons();
//}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning();
}
// MARK - Actions events
@IBAction func incorrectAnswerProvided(_ sender: UIButton) {
resultLabel.text = "INCORRECT";
q3Played();
// Send an event to track which which logo is the most difficult
MSAnalytics.trackEvent("MarkedIncorrectAnswer", withProperties: ["Logo" : (self.logoImageView.accessibilityLabel)!]);
}
@IBAction func correctAnswerProvided(_ sender: UIButton) {
resultLabel.text = "CORRECT";
updateAndShowScore();
q3Played();
}
// MARK - Other functions
func q3Played() {
UserDefaults.standard.set(true, forKey: "Q3Played");
disableAllButtons();
}
func updateAndShowScore() {
MyGlobalVariables.playerScore += 10;
displayPlayerScore();
}
func displayPlayerScore(){
currentScoreLabel.text = "Your score : " + String(MyGlobalVariables.playerScore);
}
func disableAllButtons() {
answer1Button.isEnabled = false;
answer2Button.isEnabled = false;
answer3Button.isEnabled = false;
}
}
| mit | 8a60103341aa5045b7a423f9add915fa | 27.409091 | 125 | 0.637333 | 4.92126 | false | false | false | false |
LacieJiang/Custom-2048 | Custom-2048/Custom-2048/Views/ScoreView.swift | 1 | 1003 | //
// ScoreView.swift
// Custom-2048
//
// Created by Jiang Liyin on 14-6-22.
//
import UIKit
protocol ScoreViewProtocol {
func scoreChanged(newScore: Int)
}
class ScoreView: UIView, ScoreViewProtocol {
var score: Int = 0 {
didSet {
scoreLabel.text = "SCORE: \(score)"
}
}
let defaultFrame = CGRectMake(0, 0, 140, 40)
var scoreLabel: UILabel
init(cornerRadius: CGFloat, backgroundColor bgColor: UIColor, textColor: UIColor, textFont: UIFont) {
score = 0
scoreLabel = UILabel(frame: defaultFrame)
scoreLabel.text = "SCORE: \(score)"
scoreLabel.textAlignment = .Center
if textColor != nil {
scoreLabel.textColor = textColor
}
if textFont != nil {
scoreLabel.font = textFont
}
super.init(frame: defaultFrame)
self.addSubview(self.scoreLabel)
layer.cornerRadius = cornerRadius
backgroundColor = (bgColor != nil) ? bgColor : UIColor.whiteColor()
}
func scoreChanged(newScore: Int) {
self.score = newScore
}
}
| bsd-2-clause | 989808416a0fb49bc46a7cdfd37a43c7 | 21.795455 | 103 | 0.66999 | 3.857692 | false | false | false | false |
Rehsco/ImagePersistence | ImagePersistence-Mac/ImagePersistence.swift | 1 | 6685 | //
// ImagePersistence.swift
// ImagePersistence
//
// Created by Martin Rehder on 14.03.2017.
/*
* Copyright 2017-present Martin Jacob Rehder.
* http://www.rehsco.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import Cocoa
open class ImagePersistence: ImagePersistenceInterface {
private let fileManager = FileManager.default
private let directoryURL: URL
private let storageID: String
open var imageCache = ImageCache()
public init?(storageID: String = "ipimages") {
self.storageID = storageID
let possibleDirectories = fileManager.urls(for: .documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask)
if possibleDirectories.count > 0 {
let documentDirectory = possibleDirectories[0]
let directoryURL = documentDirectory.appendingPathComponent(storageID)
self.directoryURL = directoryURL
let path = self.directoryURL.path
if !fileManager.fileExists(atPath: path) {
do {
try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
NSLog("Cannot create image directory at path \(path). Description: \(error.description)")
return nil
}
}
} else {
NSLog("Cannot create image directory")
return nil
}
}
open func filenameFromImageID(_ imageID: String, suffix: String = "png") -> String {
return "com.rehsco.imagepersistence.\(imageID).\(suffix)"
}
open func imageAsJPEG(_ image: NSImage, quality: CGFloat) -> Data {
return image.imageJPEGRepresentation(quality: quality)! as Data
}
open func imageAsPNG(_ image: NSImage) -> Data {
return image.imagePNGRepresentation()! as Data
}
open func imageFromData(_ data: Data) -> NSImage? {
return NSImage(data: data)
}
open func saveImage(_ image: NSImage, imageID: String) {
let imageData = self.imageAsPNG(image)
self.saveImageData(imageData, imageID: imageID)
self.imageCache.addImage(id: imageID, image: image)
}
open func saveImageData(_ imageData: Data, imageID: String) {
let filename = self.filenameFromImageID(imageID)
encryptAndStoreImage(imageData, filename: filename)
}
private func encryptAndStoreImage(_ imageData: Data, filename: String) {
if let data = self.encryptImage(imageData) {
let path = self.directoryURL.appendingPathComponent(filename).path
fileManager.createFile(atPath: path, contents: data, attributes: nil)
}
else {
NSLog("Cannot save image with filename \(filename)")
}
}
open func deleteImage(_ imageID: String) {
let filename = self.filenameFromImageID(imageID)
deleteImageWithFilename(filename, withFileExistsCheck: false)
self.imageCache.removeImage(id: imageID)
}
private func deleteImageWithFilename(_ filename: String, withFileExistsCheck: Bool) {
let path = self.directoryURL.appendingPathComponent(filename).path
if !withFileExistsCheck || fileManager.fileExists(atPath: path) {
do {
try fileManager.removeItem(atPath: path)
} catch {
if withFileExistsCheck {
NSLog("Cannot remove image at path \(path)")
}
}
} else {
NSLog("Cannot remove image. Cannot get path for filename \(filename)")
}
}
open func deleteAllImages() {
let path = self.directoryURL.path
self.imageCache.removeAll()
do {
let directoryContents = try fileManager.contentsOfDirectory(atPath: path)
for file in directoryContents {
let fullPath = self.directoryURL.appendingPathComponent(file).path
do {
try fileManager.removeItem(atPath: fullPath)
} catch {
NSLog("Could not delete file: \(file)")
}
}
}
catch {
NSLog("Could not access \(path)")
}
}
open func hasImageCached(_ imageID: String) -> Bool {
return self.imageCache.getImage(id: imageID) != nil
}
open func getImage(_ imageID: String) -> NSImage? {
if let image = self.imageCache.getImage(id: imageID) {
return image
}
let filename = self.filenameFromImageID(imageID)
let filePath = directoryURL.appendingPathComponent(filename).path
if let data = fileManager.contents(atPath: filePath), let imageData = self.decryptImage(data) {
if let image = self.imageFromData(imageData) {
self.imageCache.addImage(id: imageID, image: image)
return image
}
}
return nil
}
open func getImageData(_ imageID: String) -> Data? {
let filename = self.filenameFromImageID(imageID)
let filePath = directoryURL.appendingPathComponent(filename).path
if let data = fileManager.contents(atPath: filePath), let imageData = self.decryptImage(data) {
return imageData
}
return nil
}
// MARK: - Encryption (Optional)
// Override in subclass
open func encryptImage(_ data: Data) -> Data? {
return data
}
// Override in subclass
open func decryptImage(_ data: Data) -> Data? {
return data
}
}
| mit | f35ed234f181464e07b5086540c93280 | 36.768362 | 128 | 0.63261 | 4.97026 | false | false | false | false |
ivngar/TDD-TodoList | TDD-TodoList/Model/ToDoItem.swift | 1 | 1835 | //
// ToDoItem.swift
// TDD-TodoList
//
// Created by Ivan Garcia on 20/6/17.
// Copyright © 2017 Ivan Garcia. All rights reserved.
//
import Foundation
struct ToDoItem: Equatable {
let title: String
let itemDescription: String?
let timestamp: Double?
let location: Location?
private let titleKey = "titleKey"
private let itemDescriptionKey = "itemDescriptionKey"
private let timestampKey = "timestampKey"
private let locationKey = "locationKey"
var plistDict: [String:Any] {
var dict = [String:Any]()
dict[titleKey] = title
if let itemDescription = itemDescription {
dict[itemDescriptionKey] = itemDescription
}
if let timestamp = timestamp {
dict[timestampKey] = timestamp
}
if let location = location {
let locationDict = location.plistDict
dict[locationKey] = locationDict
}
return dict
}
init(title: String, itemDescription: String? = nil, timestamp: Double? = nil, location: Location? = nil) {
self.title = title
self.itemDescription = itemDescription
self.timestamp = timestamp
self.location = location
}
init?(dict: [String:Any]) {
guard let title = dict[titleKey] as? String else
{ return nil }
self.title = title
self.itemDescription = dict[itemDescriptionKey] as? String
self.timestamp = dict[timestampKey] as? Double
if let locationDict = dict[locationKey] as? [String:Any] {
self.location = Location(dict: locationDict)
} else {
self.location = nil
}
}
}
func ==(lhs: ToDoItem, rhs: ToDoItem) -> Bool {
if lhs.location != rhs.location {
return false
}
if lhs.timestamp != rhs.timestamp {
return false
}
if lhs.itemDescription != rhs.itemDescription {
return false
}
if lhs.title != rhs.title {
return false
}
return true
}
| mit | 6d9f53861ce8aeeb7bc7fcd7abfe2f13 | 24.472222 | 108 | 0.666848 | 4.066519 | false | false | false | false |
xwv/XWebView | XWebView/XWVInvocation.swift | 1 | 14229 | /*
Copyright 2015 XWebView
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
import ObjectiveC
@objc protocol NSMethodSignatureProtocol {
static func signature(objCTypes: UnsafePointer<CChar>!) -> NSMethodSignatureProtocol?
func getArgumentType(atIndex idx: UInt) -> UnsafePointer<CChar>
var numberOfArguments: UInt { get }
var frameLength: UInt { get }
var methodReturnType: UnsafePointer<CChar> { get }
var methodReturnLength: UInt { get }
func isOneWay() -> ObjCBool
}
@objc protocol NSInvocationProtocol {
static func invocation(methodSignature: AnyObject) -> NSInvocationProtocol
var selector: Selector { get set }
var target: AnyObject? { get set }
func setArgument(_ argumentLocation: UnsafeMutableRawPointer, atIndex idx: Int)
func getArgument(_ argumentLocation: UnsafeMutableRawPointer, atIndex idx: Int)
var argumentsRetained: ObjCBool { get }
func retainArguments()
func setReturnValue(_ retLoc: UnsafeMutableRawPointer)
func getReturnValue(_ retLoc: UnsafeMutableRawPointer)
func invoke()
func invoke(target: AnyObject)
var methodSignature: NSMethodSignatureProtocol { get }
}
var NSMethodSignature: NSMethodSignatureProtocol.Type = {
class_addProtocol(objc_lookUpClass("NSMethodSignature"), NSMethodSignatureProtocol.self)
return objc_lookUpClass("NSMethodSignature") as! NSMethodSignatureProtocol.Type
}()
var NSInvocation: NSInvocationProtocol.Type = {
class_addProtocol(objc_lookUpClass("NSInvocation"), NSInvocationProtocol.self)
return objc_lookUpClass("NSInvocation") as! NSInvocationProtocol.Type
}()
@discardableResult public func invoke(_ selector: Selector, of target: AnyObject, with arguments: [Any?] = [], on thread: Thread? = nil, waitUntilDone wait: Bool = true) -> Any! {
guard let method = class_getInstanceMethod(type(of: target), selector),
let sig = NSMethodSignature.signature(objCTypes: method_getTypeEncoding(method)) else {
target.doesNotRecognizeSelector?(selector)
fatalError("Unrecognized selector -[\(target) \(selector)]")
}
let inv = NSInvocation.invocation(methodSignature: sig)
// Setup arguments
precondition(arguments.count + 2 <= method_getNumberOfArguments(method),
"Too many arguments for calling -[\(type(of: target)) \(selector)]")
var args = [[Int]](repeating: [], count: arguments.count)
for i in 0 ..< arguments.count {
if let arg: Any = arguments[i] {
let code = sig.getArgumentType(atIndex: UInt(i) + 2)
let octype = ObjCType(code: code)
if octype == .object {
let obj: AnyObject = _bridgeAnythingToObjectiveC(arg)
_autorelease(obj)
args[i] = _encodeBitsAsWords(obj)
} else if octype == .clazz, let cls = arg as? AnyClass {
args[i] = _encodeBitsAsWords(cls)
} else if octype == .float, let float = arg as? Float {
// prevent to promot float type to double
args[i] = _encodeBitsAsWords(float)
} else if var val = arg as? CVarArg {
if (type(of: arg) as? AnyClass)?.isSubclass(of: NSNumber.self) == true {
// argument is an NSNumber object
if let v = (arg as! NSNumber).value(as: octype) {
val = v
}
}
args[i] = val._cVarArgEncoding
} else {
let octype = String(cString: code)
fatalError("Unable to convert argument \(i) from Swift type \(type(of: arg)) to ObjC type '\(octype)'")
}
} else {
// nil
args[i] = [Int(0)]
}
args[i].withUnsafeBufferPointer {
inv.setArgument(UnsafeMutablePointer(mutating: $0.baseAddress!), atIndex: i + 2)
}
}
if selector.family == .init_ {
// Self should be consumed for method belongs to init family
_ = Unmanaged.passRetained(target)
}
inv.selector = selector
if thread == nil || (thread == Thread.current && wait) {
inv.invoke(target: target)
} else {
let selector = #selector(NSInvocationProtocol.invoke(target:))
inv.retainArguments()
(inv as! NSObject).perform(selector, on: thread!, with: target, waitUntilDone: wait)
guard wait else { return Void() }
}
if sig.methodReturnLength == 0 { return Void() }
// Fetch the return value
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(sig.methodReturnLength))
inv.getReturnValue(buffer)
let octype = ObjCType(code: sig.methodReturnType)
defer {
if octype == .object && selector.returnsRetained {
// To balance the retained return value
let obj = UnsafeRawPointer(buffer).load(as: AnyObject.self)
Unmanaged.passUnretained(obj).release()
}
buffer.deallocate(capacity: Int(sig.methodReturnLength))
}
return octype.loadValue(from: buffer)
}
public func createInstance(of class: AnyClass, by initializer: Selector = #selector(NSObject.init), with arguments: [Any?] = []) -> AnyObject? {
guard let obj = invoke(#selector(NSProxy.alloc), of: `class`) else {
return nil
}
return invoke(initializer, of: obj as AnyObject, with: arguments) as AnyObject
}
// See: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
private enum ObjCType : CChar {
case char = 0x63 // 'c'
case int = 0x69 // 'i'
case short = 0x73 // 's'
case long = 0x6c // 'l'
case longlong = 0x71 // 'q'
case uchar = 0x43 // 'C'
case uint = 0x49 // 'I'
case ushort = 0x53 // 'S'
case ulong = 0x4c // 'L'
case ulonglong = 0x51 // 'Q'
case float = 0x66 // 'f'
case double = 0x64 // 'd'
case bool = 0x42 // 'B'
case void = 0x76 // 'v'
case string = 0x2a // '*'
case object = 0x40 // '@'
case clazz = 0x23 // '#'
case selector = 0x3a // ':'
case pointer = 0x5e // '^'
case unknown = 0x3f // '?'
init(code: UnsafePointer<CChar>) {
var val = code.pointee
if val == 0x72 {
// skip const qualifier
val = code.successor().pointee
} else if val == 0x7b {
// unbox structure type
var p = code
repeat {
p = p.successor()
} while p.pointee != 0x3d
p = p.successor()
if p.successor().pointee == 0x7d {
// support only one member
val = p.pointee
}
}
guard let type = ObjCType(rawValue: val) else {
fatalError("Unknown ObjC type code: \(String(cString: code))")
}
self = type
}
func loadValue(from pointer: UnsafeRawPointer) -> Any! {
switch self {
case .char: return pointer.load(as: CChar.self)
case .int: return pointer.load(as: CInt.self)
case .short: return pointer.load(as: CShort.self)
case .long: return pointer.load(as: Int32.self)
case .longlong: return pointer.load(as: CLongLong.self)
case .uchar: return pointer.load(as: CUnsignedChar.self)
case .uint: return pointer.load(as: CUnsignedInt.self)
case .ushort: return pointer.load(as: CUnsignedShort.self)
case .ulong: return pointer.load(as: UInt32.self)
case .ulonglong: return pointer.load(as: CUnsignedLongLong.self)
case .float: return pointer.load(as: CFloat.self)
case .double: return pointer.load(as: CDouble.self)
case .bool: return pointer.load(as: CBool.self)
case .void: return Void()
case .string: return pointer.load(as: UnsafePointer<CChar>.self)
case .object: return pointer.load(as: AnyObject!.self)
case .clazz: return pointer.load(as: AnyClass!.self)
case .selector: return pointer.load(as: Selector!.self)
case .pointer: return pointer.load(as: OpaquePointer.self)
case .unknown: fatalError("Unknown ObjC type")
}
}
}
private extension NSNumber {
func value(as type: ObjCType) -> CVarArg? {
switch type {
case .bool: return self.boolValue
case .char: return self.int8Value
case .int: return self.int32Value
case .short: return self.int16Value
case .long: return self.int32Value
case .longlong: return self.int64Value
case .uchar: return self.uint8Value
case .uint: return self.uint32Value
case .ushort: return self.uint16Value
case .ulong: return self.uint32Value
case .ulonglong: return self.uint64Value
case .float: return self.floatValue
case .double: return self.doubleValue
default: return nil
}
}
}
extension Selector {
init(getterOf property: objc_property_t) {
if let attr = property_copyAttributeValue(property, "G") {
// The property defines a custom getter selector name.
self = sel_getUid(attr)
free(attr)
} else {
self = sel_getUid(property_getName(property))
}
}
init?(setterOf property: objc_property_t) {
if let attr = property_copyAttributeValue(property, "R") {
free(attr)
return nil
}
if let attr = property_copyAttributeValue(property, "S") {
// The property defines a custom setter selector name.
self.init(String(cString: attr))
free(attr)
} else {
let name = String(cString: property_getName(property))
self.init("set\(name.prefix(1).uppercased())\(name.dropFirst()):")
}
}
init(_ method: Method) {
self = method_getName(method)
}
}
extension Selector {
enum Family : Int8 {
case none = 0
case alloc = 97
case copy = 99
case mutableCopy = 109
case init_ = 105
case new = 110
}
static var prefixes : [[CChar]] = [
/* alloc */ [97, 108, 108, 111, 99],
/* copy */ [99, 111, 112, 121],
/* mutableCopy */ [109, 117, 116, 97, 98, 108, 101, 67, 111, 112, 121],
/* init */ [105, 110, 105, 116],
/* new */ [110, 101, 119]
]
var family: Family {
// See: http://clang.llvm.org/docs/AutomaticReferenceCounting.html#id34
var s = unsafeBitCast(self, to: UnsafePointer<Int8>.self)
while s.pointee == 0x5f { s += 1 } // skip underscore
for p in Selector.prefixes {
let lowercase = CChar(97)...CChar(122)
let l = p.count
if strncmp(s, p, l) == 0 && !lowercase.contains(s.advanced(by: l).pointee) {
return Family(rawValue: s.pointee)!
}
}
return .none
}
var returnsRetained: Bool {
return family != .none
}
}
// Additional Swift types which can be represented in C type.
extension CVarArg {
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension Bool: CVarArg {
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UnicodeScalar: CVarArg {}
extension Selector: CVarArg {}
extension UnsafeRawPointer: CVarArg {}
extension UnsafeMutableRawPointer: CVarArg {}
extension UnsafeBufferPointer: CVarArg {}
extension UnsafeMutableBufferPointer: CVarArg {}
///////////////////////////////////////////////////////////////////////////////
public class XWVInvocation {
public final let target: AnyObject
private let thread: Thread?
public init(target: AnyObject, thread: Thread? = nil) {
self.target = target
self.thread = thread
}
@discardableResult public func call(_ selector: Selector, with arguments: [Any?] = []) -> Any! {
return invoke(selector, of: target, with: arguments, on: thread)
}
// No callback support, so return value is expected to lose.
public func asyncCall(_ selector: Selector, with arguments: [Any?] = []) {
invoke(selector, of: target, with: arguments, on: thread, waitUntilDone: false)
}
// Syntactic sugar for calling method
public subscript (selector: Selector) -> (Any?...)->Any! {
return {
(args: Any?...)->Any! in
self.call(selector, with: args)
}
}
}
extension XWVInvocation {
// Property accessor
public func value(of name: String) -> Any! {
guard let property = class_getProperty(type(of: target), name) else {
assertionFailure("Property '\(name)' does not exist")
return Void()
}
return call(Selector(getterOf: property))
}
public func setValue(_ value: Any!, to name: String) {
precondition(!(value is Void))
guard let property = class_getProperty(type(of: target), name) else {
assertionFailure("Property '\(name)' does not exist")
return
}
guard let setter = Selector(setterOf: property) else {
assertionFailure("Property '\(name)' is readonly")
return
}
call(setter, with: [value])
}
// Syntactic sugar for accessing property
public subscript (name: String) -> Any! {
get {
return value(of: name)
}
set {
setValue(newValue, to: name)
}
}
}
| apache-2.0 | eb98aa4248efd861194d72ba73ffdfe5 | 37.25 | 179 | 0.599199 | 4.236082 | false | false | false | false |
yannickl/Reactions | Sources/Extensions.swift | 1 | 2212 | /*
* Reactions
*
* Copyright 2016-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import Foundation
extension Sequence where Iterator.Element: Hashable {
/// Returns uniq elements in the sequence by keeping the order.
func uniq() -> [Iterator.Element] {
var alreadySeen: [Iterator.Element: Bool] = [:]
return filter { alreadySeen.updateValue(true, forKey: $0) == nil }
}
}
extension Bundle {
/// Returns the current lib bundle
class func reactionsBundle() -> Bundle {
var bundle = Bundle(for: ReactionButton.self)
if let url = bundle.url(forResource: "Reactions", withExtension: "bundle"), let podBundle = Bundle(url: url) {
bundle = podBundle
}
return bundle
}
}
extension String {
/**
Returns the string localized.
- Parameter tableName: The receiver’s string table to search. By default the method attempts to use the table in FeedbackLocalizable.strings.
*/
func localized(from tableName: String? = "FeedbackLocalizable") -> String {
return NSLocalizedString(self, tableName: tableName, bundle: .reactionsBundle(), value: self, comment: "")
}
}
| mit | 3f378091a8066ddf2ba6ba8936165ebb | 35.833333 | 144 | 0.728959 | 4.455645 | false | false | false | false |
mnito/random-number-game-example-swift | Sources/String+Substring.swift | 1 | 851 | /**
* Substring implementation for String type
* @author Michael P. Nitowski <[email protected]>
*/
public extension String {
public func substring(start: Int, length: Int) -> String {
//Allows for negative starts and lengths
let _startIndex = start >= 0 ? start : self.characters.count + start
let _endIndex = length >= 0 ? length + _startIndex : self.characters.count + length
var i = 0
var str = ""
//Chose this way because you do not need to import anything
/* Loops through entire string - could become inefficient for larger
start indexes */
for c in self.characters {
if i < _startIndex {
i += 1
continue
}
if i == _endIndex {
break
}
str += String(c)
i += 1
}
return str
}
public func substring(start: Int) -> String {
return substring(start, length: self.characters.count)
}
}
| mit | 7a5b86f5a647e116bfa3c6ce2bef2652 | 24.787879 | 85 | 0.6604 | 3.473469 | false | false | false | false |
adolfrank/Swift_practise | 23-day/23-day/HomeTableController.swift | 1 | 2782 | //
// HomeTableController.swift
// 23-day
//
// Created by Hongbo Yu on 16/5/3.
// Copyright © 2016年 Frank. All rights reserved.
//
import UIKit
class HomeTableController: UITableViewController {
@IBOutlet var homeTableView: UITableView!
var data = [
pattern(image: "1", name: "Pattern Building"),
pattern(image: "2", name: "Joe Beez"),
pattern(image: "3", name: "Car It's car"),
pattern(image: "4", name: "Floral Kaleidoscopic"),
pattern(image: "5", name: "Sprinkle Pattern"),
pattern(image: "6", name: "Palitos de queso"),
pattern(image: "7", name: "Ready to Go? Pattern"),
pattern(image: "8", name: "Sets Seamless"),
]
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = homeTableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! PatternCell
let pattern = data[indexPath.row]
cell.patternImage?.image = UIImage(named: pattern.image)
cell.patternLable?.text = pattern.name
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .Normal, title: "Delete") { action, index in
print("Delete button tapped")
}
delete.backgroundColor = UIColor.grayColor()
let share = UITableViewRowAction(style: .Normal, title: "Share") { (action: UITableViewRowAction!, indexPath: NSIndexPath) -> Void in
let firstActivityItem = self.data[indexPath.row]
let activityViewController = UIActivityViewController(activityItems: [firstActivityItem.image as NSString], applicationActivities: nil)
self.presentViewController(activityViewController, animated: true, completion: nil)
}
share.backgroundColor = UIColor.redColor()
let download = UITableViewRowAction(style: .Normal, title: "Download") { action, index in
print("Download button tapped")
}
download.backgroundColor = UIColor.blueColor()
return [download, share, delete]
}
}
| mit | 3023f43b88c30934c3655a0913f4da9c | 31.694118 | 147 | 0.641238 | 4.971377 | false | false | false | false |
PlutoMa/SwiftProjects | 014.VideoSplash/VideoSplash/VideoSplash/VedioSplashViewController.swift | 1 | 3182 | //
// VedioSplashViewController.swift
// VideoSplash
//
// Created by Dareway on 2017/10/25.
// Copyright © 2017年 Pluto. All rights reserved.
//
import UIKit
import AVKit
import MediaPlayer
enum ScalingMode {
case Resize
case ResizeAspect
case ResizeAspectFill
}
class VedioSplashViewController: UIViewController {
private let moviePlayer = AVPlayerViewController()
private var moviePlayerSoundLevel: Float = 1.0
public var contentURL = NSURL() {
didSet {
setMoviePlayer(url: contentURL)
}
}
public var videoFrame = CGRect()
public var startTime: CGFloat = 0.0
public var duration: CGFloat = 0.0
public var backgroundColor = UIColor.black {
didSet {
view.backgroundColor = backgroundColor
}
}
public var sound: Bool = true {
didSet {
if sound {
moviePlayerSoundLevel = 1.0
} else {
moviePlayerSoundLevel = 0.0
}
}
}
public var alpha: CGFloat = CGFloat() {
didSet {
moviePlayer.view.alpha = alpha
}
}
public var alwaysRepeat: Bool = true {
didSet {
if alwaysRepeat {
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: moviePlayer.player?.currentItem)
}
}
}
public var fillMode: ScalingMode = .ResizeAspectFill {
didSet {
switch fillMode {
case .Resize:
moviePlayer.videoGravity = AVLayerVideoGravity.resize.rawValue
case .ResizeAspect:
moviePlayer.videoGravity = AVLayerVideoGravity.resizeAspect.rawValue
case .ResizeAspectFill:
moviePlayer.videoGravity = AVLayerVideoGravity.resizeAspectFill.rawValue
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
moviePlayer.view.frame = videoFrame
moviePlayer.showsPlaybackControls = false
view.addSubview(moviePlayer.view)
view.sendSubview(toBack: moviePlayer.view)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
private func setMoviePlayer(url: NSURL) -> Void {
let videoCutter = VideoCutter()
videoCutter.cropVideoWithUrl(videoUrl: url, startTime: startTime, duration: duration) { (pathUrl, error) in
DispatchQueue.main.async {
if let path = pathUrl {
self.moviePlayer.player = AVPlayer(url: path as URL)
self.moviePlayer.player?.play()
self.moviePlayer.player?.volume = self.moviePlayerSoundLevel
}
}
}
}
@objc
private func playerItemDidReachEnd() -> Void {
moviePlayer.player?.seek(to: kCMTimeZero)
moviePlayer.player?.play()
}
}
| mit | 415b805f8640349ee621774cdb47124b | 28.990566 | 201 | 0.608997 | 5.307179 | false | false | false | false |
halo/LinkLiar | LinkTools/Vendors.swift | 1 | 2132 | /*
* Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import Foundation
struct Vendors {
/**
* Looks up a Vendor by its ID.
* If no vendor was found, returns nil.
*
* - parameter id: The ID of the vendor (e.g. "ibm").
*
* - returns: A `Vendor` if found and `nil` if missing.
*/
static func find(_ id: String) -> Vendor? {
let id = id.filter("0123456789abcdefghijklmnopqrstuvwxyz".contains)
guard let vendorData = MACPrefixes.dictionary[id] else { return nil }
guard let rawPrefixes = vendorData.values.first else { return nil }
guard let name = vendorData.keys.first else { return nil }
let prefixes = rawPrefixes.map { rawPrefix in
MACPrefix.init(String(format:"%06X", rawPrefix))
}
return Vendor.init(id: id, name: name, prefixes: prefixes)
}
static var available: [Vendor] {
all.filter { !Config.instance.prefixes.vendors.contains($0) }
}
private static var all: [Vendor] {
MACPrefixes.dictionary.keys.sorted().reversed().compactMap {
return find($0)
}
}
}
| mit | eab46d3fbeebf158a26348b02319a64e | 40.803922 | 133 | 0.718105 | 4.131783 | false | false | false | false |
ryoppippi/Josephus-circle-iOS-app | Josephus circle/ViewController.swift | 1 | 2928 | //
// ViewController.swift
// HelloWorld
//
// Created by 三浦亮太朗 on 2015/12/02.
// Copyright © 2015年 ICU. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBAction func comeHome (suge: UIStoryboardSegue){
}
//計算に関するものどもが以下に続く
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var Answer: UILabel!
@IBOutlet weak var people: UITextField!
@IBOutlet weak var killpp: UITextField!
let font4 = UIFont.systemFontOfSize(17)
//とりあえず計算する関数でも作っておく
func calc(num:Int, kill:Int) -> Int {
var list = [Bool] (count: num, repeatedValue: false)
if(num <= 0 || kill <= 0){
return 0
}
var check = -1
for (var a = 0; a < num; a++){
for (var c = 0; c < kill; c++) {
repeat {
check++
if (check >= num) {
check = check - num
}
} while(list[check] == true)
}
list[check] = true
}
return check+1
}
//キーボードを引っ込める
@IBAction func tapView(sender: AnyObject) {
self.view.endEditing(true)
}
@IBAction func ClcBtn(sender: AnyObject) {
let a = Int(people.text!)
let b = Int(killpp.text!)
var ans = 0
if(a <= 0 || b <= 0 || a == nil || b == nil || a > 1000 || b > 1000){
Answer.text = "1以上1000以下で入力せよ!"
Answer.textColor = UIColor.redColor()
Answer.font = UIFont.boldSystemFontOfSize(UIFont.labelFontSize())
label1.text = ""
label2.text = ""
}else{
ans = calc(a!, kill: b!)
Answer.textColor = UIColor.blackColor()
Answer.font = font4
Answer.font = UIFont.systemFontOfSize(CGFloat(35))
Answer.text = String(ans)
label1.text = "生き残るなら..."
label2.text = "番目!"
}
}
//リセットボタン
@IBAction func ResetBtn(sender: AnyObject) {
Answer.textColor = UIColor.blackColor()
Answer.font = UIFont.systemFontOfSize(UIFont.systemFontSize())
Answer.font = font4
Answer.text = "1以上1000以下で入力せよ"
label1.text = ""
label2.text = ""
people.text = ""
killpp.text = ""
}
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.
}
} | mit | 217141fca48482466e72c97c539ae095 | 25.018868 | 80 | 0.517954 | 4.102679 | false | false | false | false |
AaronMT/firefox-ios | content-blocker-lib-ios/ContentBlockerGen/Sources/ContentBlockerGenLib/ContentBlockerGenLib.swift | 6 | 3506 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
public enum Action: String {
case blockAll = "\"block\""
case blockCookies = "\"block-cookies\""
}
public enum CategoryTitle: String, CaseIterable {
case Advertising
case Analytics
case Social
// case Fingerprinting // not used, we have special fingerprinting list instead
case Disconnect
case Cryptomining
case Content
}
public class ContentBlockerGenLib {
var companyToRelatedDomains = [String: [String]]()
public init(entityListJson: [String: Any]) {
parseEntityList(json: entityListJson)
}
func parseEntityList(json: [String: Any]) {
json.forEach {
let company = $0.key
let related = ($0.value as! [String: [String]])["properties"]!
companyToRelatedDomains[company] = related
}
}
func buildUnlessDomain(_ domains: [String]) -> String {
guard domains.count > 0 else { return "" }
let result = domains.reduce("", { $0 + "\"*\($1)\"," }).dropLast()
return "[" + result + "]"
}
func buildUrlFilter(_ domain: String) -> String {
let prefix = "^https?://([^/]+\\\\.)?"
return prefix + domain.replacingOccurrences(of: ".", with: "\\\\.")
}
func buildOutputLine(urlFilter: String, unlessDomain: String, action: Action) -> String {
let unlessDomainSection = unlessDomain.isEmpty ? "" : ",\"unless-domain\":\(unlessDomain)"
let result = """
{"action":{"type":\(action.rawValue)},"trigger":{"url-filter":"\(urlFilter)","load-type":["third-party"]\(unlessDomainSection)}}
"""
return result
}
public func handleCategoryItem(_ categoryItem: Any, action: Action) -> [String] {
let categoryItem = categoryItem as! [String: [String: Any]]
var result = [String]()
assert(categoryItem.count == 1)
let companyName = categoryItem.first!.key
let relatedDomains = companyToRelatedDomains[companyName, default: []]
let unlessDomain = buildUnlessDomain(relatedDomains)
let entry = categoryItem.first!.value.first(where: { $0.key.hasPrefix("http") || $0.key.hasPrefix("www.") })!
// let companyDomain = entry.key // noting that companyDomain is not used anywhere
let domains = entry.value as! [String]
domains.forEach {
let f = buildUrlFilter($0)
let line = buildOutputLine(urlFilter: f, unlessDomain: unlessDomain, action: action)
result.append(line)
}
return result
}
public func parseBlocklist(json: [String: Any], action: Action, categoryTitle: CategoryTitle) -> [String] {
let categories = json["categories"]! as! [String: Any]
var result = [String]()
let category = categories[categoryTitle.rawValue] as! [Any]
category.forEach {
result += handleCategoryItem($0, action: action)
}
return result
}
public func parseFingerprintingList(json: [String]) -> [String] {
var result = [String]()
for domain in json {
let f = buildUrlFilter(domain)
let line = buildOutputLine(urlFilter: f, unlessDomain: "", action: .blockAll)
result.append(line)
}
return result
}
}
| mpl-2.0 | 2affcbcaa139e6e2ee1c56594d99b047 | 35.14433 | 148 | 0.609812 | 4.393484 | false | false | false | false |
creatubbles/ctb-api-swift | Pods/ObjectMapper/Sources/Mapper.swift | 4 | 15785 | //
// Mapper.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-09.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public enum MappingType {
case fromJSON
case toJSON
}
/// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects
public final class Mapper<N: BaseMappable> {
public var context: MapContext?
public var shouldIncludeNilValues = false /// If this is set to true, toJSON output will include null values for any variables that are not set.
public init(context: MapContext? = nil, shouldIncludeNilValues: Bool = false){
self.context = context
self.shouldIncludeNilValues = shouldIncludeNilValues
}
// MARK: Mapping functions that map to an existing object toObject
/// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is
public func map(JSONObject: Any?, toObject object: N) -> N {
if let JSON = JSONObject as? [String: Any] {
return map(JSON: JSON, toObject: object)
}
return object
}
/// Map a JSON string onto an existing object
public func map(JSONString: String, toObject object: N) -> N {
if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) {
return map(JSON: JSON, toObject: object)
}
return object
}
/// Maps a JSON dictionary to an existing object that conforms to Mappable.
/// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject
public func map(JSON: [String: Any], toObject object: N) -> N {
var mutableObject = object
let map = Map(mappingType: .fromJSON, JSON: JSON, toObject: true, context: context, shouldIncludeNilValues: shouldIncludeNilValues)
mutableObject.mapping(map: map)
return mutableObject
}
//MARK: Mapping functions that create an object
/// Map a JSON string to an object that conforms to Mappable
public func map(JSONString: String) -> N? {
if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) {
return map(JSON: JSON)
}
return nil
}
/// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil.
public func map(JSONObject: Any?) -> N? {
if let JSON = JSONObject as? [String: Any] {
return map(JSON: JSON)
}
return nil
}
/// Maps a JSON dictionary to an object that conforms to Mappable
public func map(JSON: [String: Any]) -> N? {
let map = Map(mappingType: .fromJSON, JSON: JSON, context: context, shouldIncludeNilValues: shouldIncludeNilValues)
if let klass = N.self as? StaticMappable.Type { // Check if object is StaticMappable
if var object = klass.objectForMapping(map: map) as? N {
object.mapping(map: map)
return object
}
} else if let klass = N.self as? Mappable.Type { // Check if object is Mappable
if var object = klass.init(map: map) as? N {
object.mapping(map: map)
return object
}
} else if let klass = N.self as? ImmutableMappable.Type { // Check if object is ImmutableMappable
do {
return try klass.init(map: map) as? N
} catch let error {
#if DEBUG
let exception: NSException
if let mapError = error as? MapError {
exception = NSException(name: .init(rawValue: "MapError"), reason: mapError.description, userInfo: nil)
} else {
exception = NSException(name: .init(rawValue: "ImmutableMappableError"), reason: error.localizedDescription, userInfo: nil)
}
exception.raise()
#endif
}
} else {
// Ensure BaseMappable is not implemented directly
assert(false, "BaseMappable should not be implemented directly. Please implement Mappable, StaticMappable or ImmutableMappable")
}
return nil
}
// MARK: Mapping functions for Arrays and Dictionaries
/// Maps a JSON array to an object that conforms to Mappable
public func mapArray(JSONString: String) -> [N]? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
if let objectArray = mapArray(JSONObject: parsedJSON) {
return objectArray
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(JSONObject: parsedJSON) {
return [object]
}
return nil
}
/// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapArray(JSONObject: Any?) -> [N]? {
if let JSONArray = JSONObject as? [[String: Any]] {
return mapArray(JSONArray: JSONArray)
}
return nil
}
/// Maps an array of JSON dictionary to an array of Mappable objects
public func mapArray(JSONArray: [[String: Any]]) -> [N] {
// map every element in JSON array to type N
#if swift(>=4.1)
let result = JSONArray.compactMap(map)
#else
let result = JSONArray.flatMap(map)
#endif
return result
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONString: String) -> [String: N]? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
return mapDictionary(JSONObject: parsedJSON)
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONObject: Any?) -> [String: N]? {
if let JSON = JSONObject as? [String: [String: Any]] {
return mapDictionary(JSON: JSON)
}
return nil
}
/// Maps a JSON dictionary of dictionaries to a dictionary of Mappable objects
public func mapDictionary(JSON: [String: [String: Any]]) -> [String: N]? {
// map every value in dictionary to type N
let result = JSON.filterMap(map)
if result.isEmpty == false {
return result
}
return nil
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONObject: Any?, toDictionary dictionary: [String: N]) -> [String: N] {
if let JSON = JSONObject as? [String : [String : Any]] {
return mapDictionary(JSON: JSON, toDictionary: dictionary)
}
return dictionary
}
/// Maps a JSON dictionary of dictionaries to an existing dictionary of Mappable objects
public func mapDictionary(JSON: [String: [String: Any]], toDictionary dictionary: [String: N]) -> [String: N] {
var mutableDictionary = dictionary
for (key, value) in JSON {
if let object = dictionary[key] {
_ = map(JSON: value, toObject: object)
} else {
mutableDictionary[key] = map(JSON: value)
}
}
return mutableDictionary
}
/// Maps a JSON object to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSONObject: Any?) -> [String: [N]]? {
if let JSON = JSONObject as? [String: [[String: Any]]] {
return mapDictionaryOfArrays(JSON: JSON)
}
return nil
}
///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) -> [String: [N]]? {
// map every value in dictionary to type N
let result = JSON.filterMap {
mapArray(JSONArray: $0)
}
if result.isEmpty == false {
return result
}
return nil
}
/// Maps an 2 dimentional array of JSON dictionaries to a 2 dimentional array of Mappable objects
public func mapArrayOfArrays(JSONObject: Any?) -> [[N]]? {
if let JSONArray = JSONObject as? [[[String: Any]]] {
var objectArray = [[N]]()
for innerJSONArray in JSONArray {
let array = mapArray(JSONArray: innerJSONArray)
objectArray.append(array)
}
if objectArray.isEmpty == false {
return objectArray
}
}
return nil
}
// MARK: Utility functions for converting strings to JSON objects
/// Convert a JSON String into a Dictionary<String, Any> using NSJSONSerialization
public static func parseJSONStringIntoDictionary(JSONString: String) -> [String: Any]? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
return parsedJSON as? [String: Any]
}
/// Convert a JSON String into an Object using NSJSONSerialization
public static func parseJSONString(JSONString: String) -> Any? {
let data = JSONString.data(using: String.Encoding.utf8, allowLossyConversion: true)
if let data = data {
let parsedJSON: Any?
do {
parsedJSON = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
} catch let error {
print(error)
parsedJSON = nil
}
return parsedJSON
}
return nil
}
}
extension Mapper {
// MARK: Functions that create model from JSON file
/// JSON file to Mappable object
/// - parameter JSONfile: Filename
/// - Returns: Mappable object
public func map(JSONfile: String) -> N? {
if let path = Bundle.main.path(forResource: JSONfile, ofType: nil) {
do {
let JSONString = try String(contentsOfFile: path)
do {
return self.map(JSONString: JSONString)
}
} catch {
return nil
}
}
return nil
}
/// JSON file to Mappable object array
/// - parameter JSONfile: Filename
/// - Returns: Mappable object array
public func mapArray(JSONfile: String) -> [N]? {
if let path = Bundle.main.path(forResource: JSONfile, ofType: nil) {
do {
let JSONString = try String(contentsOfFile: path)
do {
return self.mapArray(JSONString: JSONString)
}
} catch {
return nil
}
}
return nil
}
}
extension Mapper {
// MARK: Functions that create JSON from objects
///Maps an object that conforms to Mappable to a JSON dictionary <String, Any>
public func toJSON(_ object: N) -> [String: Any] {
var mutableObject = object
let map = Map(mappingType: .toJSON, JSON: [:], context: context, shouldIncludeNilValues: shouldIncludeNilValues)
mutableObject.mapping(map: map)
return map.JSON
}
///Maps an array of Objects to an array of JSON dictionaries [[String: Any]]
public func toJSONArray(_ array: [N]) -> [[String: Any]] {
return array.map {
// convert every element in array to JSON dictionary equivalent
self.toJSON($0)
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionary(_ dictionary: [String: N]) -> [String: [String: Any]] {
return dictionary.map { (arg: (key: String, value: N)) in
// convert every value in dictionary to its JSON dictionary equivalent
return (arg.key, self.toJSON(arg.value))
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionaryOfArrays(_ dictionary: [String: [N]]) -> [String: [[String: Any]]] {
return dictionary.map { (arg: (key: String, value: [N])) in
// convert every value (array) in dictionary to its JSON dictionary equivalent
return (arg.key, self.toJSONArray(arg.value))
}
}
/// Maps an Object to a JSON string with option of pretty formatting
public func toJSONString(_ object: N, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSON(object)
return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint)
}
/// Maps an array of Objects to a JSON string with option of pretty formatting
public func toJSONString(_ array: [N], prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONArray(array)
return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint)
}
/// Converts an Object to a JSON string with option of pretty formatting
public static func toJSONString(_ JSONObject: Any, prettyPrint: Bool) -> String? {
let options: JSONSerialization.WritingOptions = prettyPrint ? .prettyPrinted : []
if let JSON = Mapper.toJSONData(JSONObject, options: options) {
return String(data: JSON, encoding: String.Encoding.utf8)
}
return nil
}
/// Converts an Object to JSON data with options
public static func toJSONData(_ JSONObject: Any, options: JSONSerialization.WritingOptions) -> Data? {
if JSONSerialization.isValidJSONObject(JSONObject) {
let JSONData: Data?
do {
JSONData = try JSONSerialization.data(withJSONObject: JSONObject, options: options)
} catch let error {
print(error)
JSONData = nil
}
return JSONData
}
return nil
}
}
extension Mapper where N: Hashable {
/// Maps a JSON array to an object that conforms to Mappable
public func mapSet(JSONString: String) -> Set<N>? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
if let objectArray = mapArray(JSONObject: parsedJSON) {
return Set(objectArray)
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(JSONObject: parsedJSON) {
return Set([object])
}
return nil
}
/// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapSet(JSONObject: Any?) -> Set<N>? {
if let JSONArray = JSONObject as? [[String: Any]] {
return mapSet(JSONArray: JSONArray)
}
return nil
}
/// Maps an Set of JSON dictionary to an array of Mappable objects
public func mapSet(JSONArray: [[String: Any]]) -> Set<N> {
// map every element in JSON array to type N
#if swift(>=4.1)
return Set(JSONArray.compactMap(map))
#else
return Set(JSONArray.flatMap(map))
#endif
}
///Maps a Set of Objects to a Set of JSON dictionaries [[String : Any]]
public func toJSONSet(_ set: Set<N>) -> [[String: Any]] {
return set.map {
// convert every element in set to JSON dictionary equivalent
self.toJSON($0)
}
}
/// Maps a set of Objects to a JSON string with option of pretty formatting
public func toJSONString(_ set: Set<N>, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONSet(set)
return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint)
}
}
extension Dictionary {
internal func map<K, V>(_ f: (Element) throws -> (K, V)) rethrows -> [K: V] {
var mapped = [K: V]()
for element in self {
let newElement = try f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func map<K, V>(_ f: (Element) throws -> (K, [V])) rethrows -> [K: [V]] {
var mapped = [K: [V]]()
for element in self {
let newElement = try f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func filterMap<U>(_ f: (Value) throws -> U?) rethrows -> [Key: U] {
var mapped = [Key: U]()
for (key, value) in self {
if let newValue = try f(value) {
mapped[key] = newValue
}
}
return mapped
}
}
| mit | 2bcde0ac724b85151d7fce5046817793 | 31.214286 | 145 | 0.694583 | 3.830381 | false | false | false | false |
parkera/swift | test/Distributed/Runtime/distributed_actor_init_local.swift | 2 | 1866 | // RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-distributed -parse-as-library) | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: distributed
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
// REQUIRES: rdar78290608
import _Distributed
@available(SwiftStdlib 5.5, *)
distributed actor LocalWorker {
}
// ==== Fake Transport ---------------------------------------------------------
@available(SwiftStdlib 5.5, *)
struct ActorAddress: ActorIdentity {
let address: String
init(parse address : String) {
self.address = address
}
}
@available(SwiftStdlib 5.5, *)
struct FakeTransport: ActorTransport {
func decodeIdentity(from decoder: Decoder) throws -> AnyActorIdentity {
fatalError("not implemented:\(#function)")
}
func resolve<Act>(_ identity: Act.ID, as actorType: Act.Type)
throws -> ActorResolved<Act>
where Act: DistributedActor {
fatalError("not implemented:\(#function)")
}
func assignIdentity<Act>(_ actorType: Act.Type) -> AnyActorIdentity
where Act: DistributedActor {
let id = ActorAddress(parse: "xxx")
print("assign type:\(actorType), id:\(id)")
return .init(id)
}
func actorReady<Act>(_ actor: Act) where Act: DistributedActor {
print("ready actor:\(actor), id:\(actor.id)")
}
func resignIdentity(_ id: AnyActorIdentity) {
print("ready id:\(id)")
}
}
// ==== Execute ----------------------------------------------------------------
@available(SwiftStdlib 5.5, *)
func test() {
let transport = FakeTransport()
_ = LocalWorker(transport: transport)
// CHECK: assign type:LocalWorker, id:[[ID:.*]]
// CHECK: ready actor:main.LocalWorker, id:AnyActorIdentity([[ID]])
}
@available(SwiftStdlib 5.5, *)
@main struct Main {
static func main() async {
test()
}
}
| apache-2.0 | adf83be61f0a735395889a5d2de71d16 | 24.561644 | 111 | 0.63612 | 4.065359 | false | false | false | false |
FoodForTech/Handy-Man | HandyMan/HandyMan/Features/Login/Models/UserCredentials.swift | 1 | 1041 | //
// UserCredentials.swift
// HandyMan
//
// Created by Don Johnson on 4/15/16.
// Copyright © 2016 Don Johnson. All rights reserved.
//
import Freddy
struct UserCredentials {
let firstName: String
let lastName: String
let emailAddress: String
let password: String
init(firstName: String = "", lastName: String = "", emailAddress: String, password: String) {
self.firstName = firstName
self.lastName = lastName
self.emailAddress = emailAddress
self.password = password
}
func isValid() -> Bool {
return !emailAddress.isEmpty && !password.isEmpty
}
}
extension UserCredentials: JSONEncodable {
func toJSON() -> JSON {
let parameters = ["firstName" : self.firstName.toJSON(),
"lastName" : self.lastName.toJSON(),
"emailAddress" : self.emailAddress.toJSON(),
"password" : self.password.toJSON()]
return .dictionary(parameters)
}
}
| mit | 44bdacf8b1ef8dbaff04508c6fbddea9 | 24.365854 | 97 | 0.590385 | 4.727273 | false | false | false | false |
adrfer/swift | test/1_stdlib/Strideable.swift | 2 | 4833 | //===--- Strideable.swift - Tests for strided iteration -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
//
// XFAIL: interpret
import StdlibUnittest
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif
// Check that the generic parameter is called 'Element'.
protocol TestProtocol1 {}
extension StrideToGenerator where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension StrideTo where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension StrideThroughGenerator where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension StrideThrough where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
var StrideTestSuite = TestSuite("Strideable")
struct R : RandomAccessIndexType {
typealias Distance = Int
var x: Int
init(_ x: Int) {
self.x = x
}
func successor() -> R {
return R(x + 1)
}
func predecessor() -> R {
return R(x - 1)
}
func distanceTo(rhs: R) -> Int {
return rhs.x - x
}
func advancedBy(n: Int) -> R {
return R(x + n)
}
func advancedBy(n: Int, limit: R) -> R {
let d = distanceTo(limit)
if d == 0 || (d > 0 ? d <= n : d >= n) {
return limit
}
return self.advancedBy(n)
}
}
StrideTestSuite.test("Double") {
// Doubles are not yet ready for testing, since they still conform
// to RandomAccessIndexType
}
StrideTestSuite.test("HalfOpen") {
func check(from start: Int, to end: Int, by stepSize: Int, sum: Int) {
// Work on Ints
expectEqual(
sum,
start.stride(to: end, by: stepSize).reduce(0, combine: +))
// Work on an arbitrary RandomAccessIndexType
expectEqual(
sum,
R(start).stride(to: R(end), by: stepSize).reduce(0) { $0 + $1.x })
}
check(from: 1, to: 15, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13
check(from: 1, to: 16, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13
check(from: 1, to: 17, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16
check(from: 1, to: -13, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11
check(from: 1, to: -14, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11
check(from: 1, to: -15, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14
check(from: 4, to: 16, by: -3, sum: 0)
check(from: 1, to: -16, by: 3, sum: 0)
}
StrideTestSuite.test("Closed") {
func check(from start: Int, through end: Int, by stepSize: Int, sum: Int) {
// Work on Ints
expectEqual(
sum,
start.stride(through: end, by: stepSize).reduce(0, combine: +))
// Work on an arbitrary RandomAccessIndexType
expectEqual(
sum,
R(start).stride(through: R(end), by: stepSize).reduce(0) { $0 + $1.x })
}
check(from: 1, through: 15, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13
check(from: 1, through: 16, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16
check(from: 1, through: 17, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16
check(from: 1, through: -13, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11
check(from: 1, through: -14, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14
check(from: 1, through: -15, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14
check(from: 4, through: 16, by: -3, sum: 0)
check(from: 1, through: -16, by: 3, sum: 0)
}
StrideTestSuite.test("OperatorOverloads") {
var r1 = R(50)
var r2 = R(70)
var stride: Int = 5
if true {
var result = r1 + stride
expectType(R.self, &result)
expectEqual(55, result.x)
}
if true {
var result = stride + r1
expectType(R.self, &result)
expectEqual(55, result.x)
}
if true {
var result = r1 - stride
expectType(R.self, &result)
expectEqual(45, result.x)
}
if true {
var result = r1 - r2
expectType(Int.self, &result)
expectEqual(-20, result)
}
if true {
var result = r1
result += stride
expectType(R.self, &result)
expectEqual(55, result.x)
}
if true {
var result = r1
result -= stride
expectType(R.self, &result)
expectEqual(45, result.x)
}
}
runAllTests()
| apache-2.0 | 156ef78a46d8f3048b21c0524bb512d1 | 25.85 | 80 | 0.594869 | 3.213431 | false | true | false | false |
JohnPJenkins/swift-t | stc/tests/751-pragma-2.swift | 3 | 719 |
/*
* Test that we can define new work types and use them for foreign
* functions.
*/
import io;
pragma worktypedef a_new_work_type;
@dispatch=a_new_work_type
(void o) f1(int i) "turbine" "0.0" [
"puts \"f1(<<i>>) ran on $turbine::mode ([ adlb::rank ])\""
];
// Should not be case-sensitive
@dispatch=A_NEW_WORK_TYPE
(void o) f2(int i) "turbine" "0.0" [
"puts \"f2(<<i>>) ran on $turbine::mode ([ adlb::rank ])\""
];
@dispatch=WORKER
(void o) f3(int i) "turbine" "0.0" [
"puts \"f3(<<i>>) ran on $turbine::mode ([ adlb::rank ])\""
];
main () {
// Try to trick into running in wrong context
f1(1) =>
f2(1) =>
f3(1);
f3(2) =>
f1(2) =>
f2(2);
f1(3) =>
f3(3) =>
f2(3);
}
| apache-2.0 | d252cd449ef0f4f1af2c9450f61b982c | 16.536585 | 66 | 0.547983 | 2.453925 | false | false | false | false |
avito-tech/Paparazzo | Paparazzo/Core/VIPER/MediaPicker/View/Controls/PhotoControlsView.swift | 1 | 4170 | import UIKit
final class PhotoControlsView: UIView, ThemeConfigurable {
struct ModeOptions: OptionSet {
let rawValue: Int
static let hasRemoveButton = ModeOptions(rawValue: 1 << 0)
static let hasAutocorrectButton = ModeOptions(rawValue: 1 << 1)
static let hasCropButton = ModeOptions(rawValue: 1 << 2)
static let allButtons: ModeOptions = [.hasRemoveButton, .hasAutocorrectButton, .hasCropButton]
}
typealias ThemeType = MediaPickerRootModuleUITheme
// MARK: - Subviews
private let removeButton = UIButton()
private let autocorrectButton = UIButton()
private let cropButton = UIButton()
private var buttons = [UIButton]()
// MARK: UIView
override init(frame: CGRect) {
self.mode = [.hasRemoveButton, .hasCropButton]
super.init(frame: frame)
backgroundColor = .white
removeButton.addTarget(
self,
action: #selector(onRemoveButtonTap(_:)),
for: .touchUpInside
)
autocorrectButton.addTarget(
self,
action: #selector(onAutocorrectButtonTap(_:)),
for: .touchUpInside
)
cropButton.addTarget(
self,
action: #selector(onCropButtonTap(_:)),
for: .touchUpInside
)
addSubview(removeButton)
addSubview(autocorrectButton)
addSubview(cropButton)
buttons = [removeButton, autocorrectButton, cropButton]
setUpAccessibilityIdentifiers()
}
private func setUpAccessibilityIdentifiers() {
removeButton.setAccessibilityId(.removeButton)
autocorrectButton.setAccessibilityId(.autocorrectButton)
cropButton.setAccessibilityId(.cropButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let visibleButtons = buttons.filter { $0.isHidden == false }
visibleButtons.enumerated().forEach { index, button in
button.size = CGSize.minimumTapAreaSize
button.center = CGPoint(
x: (width * (2.0 * CGFloat(index) + 1.0)) / (2.0 * CGFloat(visibleButtons.count)),
y: bounds.centerY
)
}
}
// MARK: - ThemeConfigurable
func setTheme(_ theme: ThemeType) {
backgroundColor = theme.photoControlsViewBackgroundColor
removeButton.setImage(theme.removePhotoIcon, for: .normal)
autocorrectButton.setImage(theme.autocorrectPhotoIconInactive, for: .normal)
autocorrectButton.setImage(theme.autocorrectPhotoIconActive, for: .highlighted)
autocorrectButton.setImage(theme.autocorrectPhotoIconActive, for: .selected)
cropButton.setImage(theme.cropPhotoIcon, for: .normal)
}
// MARK: - PhotoControlsView
var onRemoveButtonTap: (() -> ())?
var onAutocorrectButtonTap: (() -> ())?
var onCropButtonTap: (() -> ())?
var onCameraButtonTap: (() -> ())?
var mode: ModeOptions {
didSet {
removeButton.isHidden = !mode.contains(.hasRemoveButton)
autocorrectButton.isHidden = !mode.contains(.hasAutocorrectButton)
cropButton.isHidden = !mode.contains(.hasCropButton)
setNeedsLayout()
}
}
func setControlsTransform(_ transform: CGAffineTransform) {
removeButton.transform = transform
autocorrectButton.transform = transform
cropButton.transform = transform
}
func setAutocorrectButtonSelected(_ selected: Bool) {
autocorrectButton.isSelected = selected
}
// MARK: - Private
@objc private func onRemoveButtonTap(_: UIButton) {
onRemoveButtonTap?()
}
@objc private func onAutocorrectButtonTap(_: UIButton) {
onAutocorrectButtonTap?()
}
@objc private func onCropButtonTap(_: UIButton) {
onCropButtonTap?()
}
}
| mit | d5daba0535e6d13544f2854da1d7d1cc | 30.119403 | 102 | 0.613189 | 5.135468 | false | false | false | false |
buscarini/JMSSwiftParse | JMSSwiftParse.playground/section-1.swift | 1 | 1468 | // Playground - noun: a place where people can play
import UIKit
import JMSSwiftParse
class TestClass {
var name = ""
var email = ""
var requiredUrl : NSURL = NSURL(string : "blah")!
var optionalUrl : NSURL? = NSURL()
var available = false
var availableString = ""
var amount = 0
var date = NSDate()
}
// MARK: Parse values
let a = TestClass()
let valid = parse(&a.name,"Pepe", longerThan(5) || shorterThan(20)) &&
parse(&a.email,"[email protected]", isEmail) &&
parse(&a.available,"true") &&
parse(&a.requiredUrl,"http://www.google.com")
a
// MARK: Parse JSON
let jsonString = "{ \"name\" : \"Antonio\",\"email\" : \"[email protected]\",\"available\" : \"TRUE\", \"url\" : \"http://www.google.com\", \"date\" : \"22.7.2010 10:02\",\"amount\" : \"22\", \"other_amount\" : \"33\" }"
var error : NSError?
let dic: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, options: .MutableLeaves, error: &error)
if let validDic = dic as? NSDictionary {
let jsonValid = parse(&a.name,validDic["name"], longerThan(8) || shorterThan(20))
&& parse(&a.date,validDic["date"],"dd.M.yyyy HH:mm")
&& parse(&a.email,validDic["email"], isEmail)
&& parse(&a.available,validDic["available"])
&& parse(&a.requiredUrl,validDic["url"])
&& parse(&a.optionalUrl,validDic["url"])
&& parse(&a.amount,validDic["amount"])
}
else {
NSLog("No dictionary")
}
a
| mit | db82a125e310231a0b7b3f58028c0a0e | 28.36 | 220 | 0.64782 | 3.198257 | false | false | false | false |
ibari/ios-twitter | Pods/RelativeFormatter/Source/RelativeFormatter.swift | 1 | 6608 | //
// RelativeFormatter.swift
// RelativeFormatter
//
// Created by David Collado Sela on 12/5/15.
// Copyright (c) 2015 David Collado Sela. All rights reserved.
//
import Foundation
public enum Precision{
case Year,Month,Week,Day,Hour,Minute,Second
}
extension NSDate{
public func relativeFormatted(idiomatic:Bool=false,precision:Precision=Precision.Second)->String{
let calendar = NSCalendar.currentCalendar()
let unitFlags = NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitWeekOfYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitSecond
let now = NSDate()
let formattedDateData:(key:String,count:Int?)
if(self.timeIntervalSince1970 < now.timeIntervalSince1970){
let components:NSDateComponents = calendar.components(unitFlags, fromDate: self, toDate: now, options: nil)
formattedDateData = RelativeFormatter.getPastKeyAndCount(components,idiomatic:idiomatic,precision:precision)
}else{
let components:NSDateComponents = calendar.components(unitFlags, fromDate: now, toDate: self, options: nil)
formattedDateData = RelativeFormatter.getFutureKeyAndCount(components,idiomatic:idiomatic,precision:precision)
}
return LocalizationHelper.localize(formattedDateData.key,count:formattedDateData.count)
}
}
class RelativeFormatter {
class func getPastKeyAndCount(components:NSDateComponents,idiomatic:Bool,precision:Precision)->(key:String,count:Int?){
var key = ""
var count:Int?
if(components.year >= 2){
count = components.year
key = "yearsago"
}
else if(components.year >= 1){
key = "yearago"
}
else if(components.year == 0 && precision == Precision.Year){
return ("thisyear",nil)
}
else if(components.month >= 2){
count = components.month
key = "monthsago"
}
else if(components.month >= 1){
key = "monthago"
}
else if(components.month == 0 && precision == Precision.Month){
return ("thismonth",nil)
}
else if(components.weekOfYear >= 2){
count = components.weekOfYear
key = "weeksago"
}
else if(components.weekOfYear >= 1){
key = "weekago"
}
else if(components.weekOfYear == 0 && precision == Precision.Week){
return ("thisweek",nil)
}
else if(components.day >= 2){
count = components.day
key = "daysago"
}
else if(components.day >= 1){
key = "dayago"
if(idiomatic){
key = key + "-idiomatic"
}
}
else if(components.day == 0 && precision == Precision.Day){
return ("today",nil)
}
else if(components.hour >= 2){
count = components.hour
key = "hoursago"
}
else if(components.hour >= 1){
key = "hourago"
}
else if(components.hour == 0 && precision == Precision.Hour){
return ("thishour",nil)
}
else if(components.minute >= 2){
count = components.minute
key = "minutesago"
}
else if(components.minute >= 1){
key = "minuteago"
}
else if(components.minute == 0 && precision == Precision.Minute){
return ("thisminute",nil)
}
else if(components.second >= 2){
count = components.second
key = "secondsago"
if(idiomatic){
key = key + "-idiomatic"
}
}
else{
key = "secondago"
if(idiomatic){
key = "now"
}
}
return (key,count)
}
class func getFutureKeyAndCount(components:NSDateComponents,idiomatic:Bool,precision:Precision)->(key:String,count:Int?){
var key = ""
var count:Int?
println(components.year)
if(components.year >= 2){
println(components.year)
count = components.year
key = "yearsahead"
}
else if(components.year >= 1){
key = "yearahead"
}
else if(components.year == 0 && precision == Precision.Year){
return ("thisyear",nil)
}
else if(components.month >= 2){
count = components.month
key = "monthsahead"
}
else if(components.month >= 1){
key = "monthahead"
}
else if(components.month == 0 && precision == Precision.Month){
return ("thismonth",nil)
}
else if(components.weekOfYear >= 2){
count = components.weekOfYear
key = "weeksahead"
}
else if(components.weekOfYear >= 1){
key = "weekahead"
}
else if(components.weekOfYear == 0 && precision == Precision.Week){
return ("thisweek",nil)
}
else if(components.day >= 2){
count = components.day
key = "daysahead"
}
else if(components.day >= 1){
key = "dayahead"
if(idiomatic){
key = key + "-idiomatic"
}
}
else if(components.day == 0 && precision == Precision.Day){
return ("today",nil)
}
else if(components.hour >= 2){
count = components.hour
key = "hoursahead"
}
else if(components.hour >= 1){
key = "hourahead"
}
else if(components.hour == 0 && precision == Precision.Hour){
return ("thishour",nil)
}
else if(components.minute >= 2){
count = components.minute
key = "minutesahead"
}
else if(components.minute >= 1){
key = "minuteahead"
}
else if(components.minute == 0 && precision == Precision.Minute){
return ("thisminute",nil)
}
else if(components.second >= 2){
count = components.second
key = "secondsahead"
if(idiomatic){
key = key + "-idiomatic"
}
}
else{
key = "secondahead"
if(idiomatic){
key = "now"
}
}
return (key,count)
}
}
| gpl-2.0 | d815adfd8d742ad16a66da8b7e02b80f | 31.551724 | 269 | 0.533444 | 4.640449 | false | false | false | false |
kusl/swift | test/decl/var/usage.swift | 3 | 7470 | // RUN: %target-parse-verify-swift
// <rdar://problem/20872721> QoI: warn about unused variables
// <rdar://problem/15975935> warning that you can use 'let' not 'var'
// <rdar://problem/18876585> Compiler should warn me if I set a parameter as 'var' but never modify it
func basicTests() -> Int {
let x = 42 // expected-warning {{immutable value 'x' was never used; consider replacing with assignment to '_' or removing it}} {{3-8=_}}
var y = 12 // expected-warning {{variable 'y' was never mutated; consider changing to 'let' constant}} {{3-6=let}}
_ = 42 // ok
_ = 42 // ok
return y
}
// expected-warning@+2 {{Use of 'var' binding here is deprecated and will be removed in a future version of Swift}} {{41-45=}}
// expected-warning@+1 {{Use of 'var' binding here is deprecated and will be removed in a future version of Swift}} {{54-58=}}
func mutableParameter(a : Int, h : Int, var i : Int, var j: Int,
var g : Int) -> Int { // expected-warning {{Use of 'var' binding here is deprecated and will be removed in a future version of Swift}} {{8-12=}}
g += 1
swap(&i, &j)
return i+g
}
struct X {
func f() {}
mutating func g() {}
}
func testStruct() {
let a = X()
a.f()
var b = X()
b.g()
var c = X() // expected-warning {{variable 'c' was never mutated; consider changing to 'let' constant}} {{3-6=let}}
c.f()
}
func takeClosure(fn : () -> ()) {}
class TestClass {
func f() {
takeClosure { [weak self] in // self is mutable but never mutated. Ok because it is weak
self?.f()
}
}
}
func nestedFunction() -> Int {
var x = 42 // No warning about being never-set.
func g() {
x = 97
var q = 27 // expected-warning {{variable 'q' was never used}} {{5-10=_}}
}
g()
return x
}
func neverRead() {
var x = 42 // expected-warning {{variable 'x' was written to, but never read}}
x = 97
x = 123
}
func property() -> Int {
var p : Int { // everything ok
return 42
}
return p
}
func testInOut(inout x : Int) { // Ok.
}
struct TestStruct {
var property = 42
}
func testStructMember() -> TestStruct {
var x = TestStruct() // ok
x.property = 17
return x
}
func testSubscript() -> [Int] {
var x = [1,2,3] // ok
x[1] = 27
return x
}
func testTuple(var x : Int) -> Int { // expected-warning {{Use of 'var' binding here is deprecated and will be removed in a future version of Swift}} {{16-19=}}
var y : Int // Ok, stored by a tuple
(x, y) = (1,2)
return y
}
struct TestComputedPropertyStruct {
var x : Int {
get {}
nonmutating set {}
}
}
func test() {
let v = TestComputedPropertyStruct()
v.x = 42
var v2 = TestComputedPropertyStruct() // expected-warning {{variable 'v2' was never mutated; consider changing to 'let' constant}} {{3-6=let}}
v2.x = 42
}
func test4() {
// expected-warning @+1 {{variable 'dest' was never mutated; consider changing to 'let' constant}} {{3-6=let}}
var dest = UnsafeMutablePointer<Int>(bitPattern: 0)
dest[0] = 0
}
func testTuple() {
var tup : (x:Int, y:Int) // expected-warning {{variable 'tup' was written to, but never read}}
tup.x = 1
// <rdar://problem/20927707> QoI: 'variable was never mutated' noisy when only part of a destructured tuple is mutated
var (tupA, tupB) = (1,2) // don't warn about tupB being changeable to a 'let'.
tupA += tupB
}
/// <rdar://problem/20911927> False positive in the "variable was never mutated" warning with IUO
func testForceValueExpr() {
var a: X! = nil // no warning, mutated through the !
a!.g()
}
// <rdar://problem/20894455> "variable was never mutated" diagnostic does not take #if into account
func testBuildConfigs() {
let abc = 42 // no warning.
var mut = 18 // no warning.
#if false
mut = abc // These uses prevent abc/mut from being unused/unmutated.
#endif
}
// <rdar://problem/21091625> Bogus 'never mutated' warning when protocol variable is mutated only by mutating method
protocol Fooable {
mutating func mutFoo()
func immutFoo()
}
func testOpenExistential(var x: Fooable, // expected-warning {{Use of 'var' binding here is deprecated and will be removed in a future version of Swift}} {{26-29=}}
y: Fooable) {
x.mutFoo()
y.immutFoo()
}
func couldThrow() throws {}
func testFixitsInStatementsWithPatterns(a : Int?) {
// FIXME: rdar://problem/23378003
// This will eventually be an error.
if var b = a, // expected-warning {{Use of 'var' binding here is deprecated and will be removed in a future version of Swift}} {{6-9=let}}
var b2 = a { // expected-warning {{Use of 'var' binding here is deprecated and will be removed in a future version of Swift}} {{7-10=let}}
b = 1
b2 = 1
_ = b
_ = b2
}
var g = [1,2,3].generate()
// FIXME: rdar://problem/23378003
// This will eventually be an error.
while var x = g.next() { // expected-warning {{Use of 'var' binding here is deprecated and will be removed in a future version of Swift}} {{9-12=let}}
x = 0
_ = x
}
// FIXME: rdar://problem/23378003
// This will eventually be an error.
guard var y = Optional.Some(1) else { // expected-warning {{Use of 'var' binding here is deprecated and will be removed in a future version of Swift}} {{9-12=let}}
return
}
y = 0
_ = y
// FIXME: rdar://problem/23378003
// This will eventually be an error.
for var b in [42] { // expected-warning {{Use of 'var' binding here is deprecated and will be removed in a future version of Swift}} {{7-11=}}
b = 42
_ = b
}
for let b in [42] { // expected-error {{'let' pattern is already in an immutable context}} {{7-11=}}
_ = b
}
do {
try couldThrow()
// FIXME: rdar://problem/23378003
// This will eventually be an error.
} catch var err { // expected-warning {{Use of 'var' binding here is deprecated and will be removed in a future version of Swift}} {{11-14=let}}
// expected-warning@-1 {{variable 'err' was never mutated; consider changing to 'let' constant}}
_ = err
}
switch a {
// FIXME: rdar://problem/23378003
// This will eventually be an error.
case var b: // expected-warning {{Use of 'var' binding here is deprecated and will be removed in a future version of Swift}} {{10-13=let}}
// expected-warning@-1 {{variable 'b' was never mutated; consider changing to 'let' constant}}
_ = b
}
}
// <rdar://22774938> QoI: "never used" in an "if let" should rewrite expression to use != nil
func test(a : Int?, b : Any) {
if true == true, let x = a { // expected-warning {{immutable value 'x' was never used; consider replacing with '_' or removing it}} {{24-25=_}}
}
if let x = a, y = a { // expected-warning {{immutable value 'x' was never used; consider replacing with '_' or removing it}} {{10-11=_}}
_ = y
}
// Simple case, insert a comparison with nil.
if let x = a { // expected-warning {{value 'x' was defined but never used; consider replacing with boolean test}} {{6-14=}} {{15-15= != nil}}
}
// General case, need to insert parentheses.
if let x = a ?? a {} // expected-warning {{value 'x' was defined but never used; consider replacing with boolean test}} {{6-14=(}} {{20-20=) != nil}}
// Special case, we can turn this into an 'is' test.
if let x = b as? Int { // expected-warning {{value 'x' was defined but never used; consider replacing with boolean test}} {{6-14=}} {{16-19=is}}
}
}
| apache-2.0 | 2c2e614cfbe94fb48fb8bc00759b9fd8 | 28.409449 | 165 | 0.63012 | 3.448753 | false | true | false | false |
qds-hoi/suracare | suracare/suracare/Core/CommonUI/AudioVisualization/KMVoiceRecordHUD.swift | 6 | 1556 | //
// KMVoiceRecordHUD.swift
// VoiceMemos
//
// Created by Zhouqi Mo on 2/24/15.
// Copyright (c) 2015 Zhouqi Mo. All rights reserved.
//
import UIKit
@IBDesignable
class KMVoiceRecordHUD: UIView {
@IBInspectable var rate: CGFloat = 0.0
@IBInspectable var fillColor: UIColor = UIColor.greenColor() {
didSet {
setNeedsDisplay()
}
}
var image: UIImage! {
didSet {
setNeedsDisplay()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
image = UIImage(named: "Mic")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
image = UIImage(named: "Mic")
}
func update(rate: CGFloat) {
self.rate = rate
setNeedsDisplay()
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextTranslateCTM(context, 0, bounds.size.height)
CGContextScaleCTM(context, 1, -1)
CGContextDrawImage(context, bounds, image.CGImage)
CGContextClipToMask(context, bounds, image.CGImage)
CGContextSetFillColor(context, CGColorGetComponents(fillColor.CGColor))
CGContextFillRect(context, CGRectMake(0, 0, bounds.width, bounds.height * rate))
}
override func prepareForInterfaceBuilder() {
let bundle = NSBundle(forClass: self.dynamicType)
image = UIImage(named: "Mic", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection)
}
}
| mit | 5e8fe634d72241cfcfe782b7b9e5211f | 26.298246 | 108 | 0.626607 | 4.644776 | false | false | false | false |
tbergmen/TableViewModel | Example/TableViewModel/ViewController.swift | 1 | 5987 | /*
Copyright (c) 2016 Tunca Bergmen <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import UIKit
import TableViewModel
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var tableViewModel: TableViewModel!
var topSection: TableSection!
override func viewDidLoad() {
super.viewDidLoad()
tableViewModel = TableViewModel(tableView: self.tableView)
addFeedSection()
addRemovableSection()
self.performSelector(#selector(ViewController.insertGiveFeedbackRow), withObject: nil, afterDelay: 3)
self.performSelector(#selector(ViewController.insertRemovableRow), withObject: nil, afterDelay: 5)
self.performSelector(#selector(ViewController.insertFeedRow), withObject: nil, afterDelay: 7)
}
func addFeedSection() {
// Create the section and add it to the model
topSection = TableSection()
topSection.headerTitle = "Newsfeed"
topSection.headerHeight = 30
tableViewModel.addSection(topSection)
// Get the sample data for this section
let sampleFeed = FeedItem.initialItems()
// Create rows for feed items
for feedItem in sampleFeed {
// Create a row for each feed item
let row = TableRow(cellIdentifier: "FeedCell")
// Configure the cell
configureFeedRow(row, withFeedItem: feedItem)
// Add the row to the section
topSection.addRow(row)
}
// Add a spacer to the bottom of the section
topSection.addRow(TableRow(cellIdentifier: "SpacerCell"))
}
func onLike(feedItem: FeedItem) {
self.alert("Liked: \(feedItem.user.name)")
}
func onShare(feedItem: FeedItem) {
self.alert("Shared: \(feedItem.user.name)")
}
func addRemovableSection() {
// Create the section and add it to the model
let removableSection = TableSection()
tableViewModel.addSection(removableSection)
// Create the header for the section and set it as the header view of section
let removableSectionHeader = NSBundle.mainBundle().loadNibNamed("RemovableSectionHeader", owner: nil, options: nil)[0] as! RemovableSectionHeader
removableSection.headerView = removableSectionHeader
removableSection.headerHeight = 30
// When remove button is tapped on the header view, remove the section from the model
removableSectionHeader.onRemoveTap {
self.tableViewModel.removeSection(removableSection)
}
// Create rows for sample feed items
let removableItems = FeedItem.removableSectionItems()
for feedItem in removableItems {
let row = TableRow(cellIdentifier: "FeedCell")
configureFeedRow(row, withFeedItem: feedItem)
removableSection.addRow(row)
}
// Add a specer to the bottom of the section
removableSection.addRow(TableRow(cellIdentifier: "SpacerCell"))
}
func insertGiveFeedbackRow() {
topSection.rowAnimation = UITableViewRowAnimation.Top
let row = TableRow(cellIdentifier: "GiveFeedbackCell")
row.onSelect {
row in
self.alert("Feedback row clicked!")
}
topSection.insertRow(row, atIndex: 0)
}
func insertRemovableRow() {
topSection.rowAnimation = UITableViewRowAnimation.Right
let row = TableRow(cellIdentifier: "RemovableCell")
row.onSelect {
row in
self.topSection.removeRow(row)
}
topSection.insertRow(row, atIndex: 1)
}
func insertFeedRow() {
topSection.rowAnimation = UITableViewRowAnimation.Left
let feedItem = FeedItem.toBeAddedLater()
let row = TableRow(cellIdentifier: "FeedCell")
configureFeedRow(row, withFeedItem: feedItem)
topSection.insertRow(row, atIndex: topSection.numberOfRows() - 1)
}
func configureFeedRow(row: TableRow, withFeedItem feedItem: FeedItem) {
row.configureCell {
cell in
let feedCell = cell as! FeedCell
feedCell.feedItem = feedItem
feedCell.onLike = self.onLike
feedCell.onShare = self.onShare
// Cell height will change based on length of the comment. FeedCell will calculate
// own height based on the feedItem given. We need to set this value as the height
// of row.
row.height = feedCell.cellHeight
}
}
func alert(message: String) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) {
action in
self.dismissViewControllerAnimated(true, completion: nil)
}
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
}
}
| mit | a1543f63fde45c0abc23b99762c2de1f | 35.95679 | 153 | 0.680641 | 4.911403 | false | false | false | false |
Spincoaster/SoundCloudKit | Source/APIClient.swift | 1 | 7761 | //
// APIClient.swift
// SoundCloudKit
//
// Created by Hiroki Kumamoto on 3/21/15.
// Copyright (c) 2015 Spincoaster. All rights reserved.
//
import SwiftyJSON
import Alamofire
public protocol JSONInitializable {
init(json: JSON)
}
public typealias RequestCallback = (URLRequest?, HTTPURLResponse?, Result<Any>) -> Void
open class APIClient {
public typealias AccessToken = String
open var manager: Alamofire.SessionManager
public static var baseURLString = "https://api.soundcloud.com"
public static var shared: APIClient = APIClient()
open var clientId = ""
open var accessToken: AccessToken?
open var isLoggedIn: Bool { return accessToken != nil }
public init() {
manager = Alamofire.SessionManager(configuration: URLSessionConfiguration.ephemeral)
}
open func fetch(_ route: Router, callback: @escaping RequestCallback) -> DataRequest {
return self.manager.request(RouterRequest(router: route, client: self))
.validate(statusCode: 200..<300).responseJSON(options: .allowFragments) { response in
callback(response.request, response.response, response.result)
}
}
open func fetchItem<T: JSONInitializable>(_ route: Router, callback: @escaping (URLRequest?, HTTPURLResponse?, Result<T>) -> Void) -> DataRequest {
return manager
.request(RouterRequest(router: route, client: self))
.validate(statusCode: 200..<300)
.responseJSON(options: .allowFragments) { response in
if let e = response.result.error {
callback(response.request, response.response, Result.failure(e))
} else {
callback(response.request, response.response, Result.success(T(json: JSON(response.result.value!))))
}
}
}
open func fetchItems<T: JSONInitializable>(_ route: Router, callback: @escaping (URLRequest?, HTTPURLResponse?, Result<[T]>) -> Void) -> DataRequest {
return manager
.request(RouterRequest(router: route, client: self))
.validate(statusCode: 200..<300)
.responseJSON(options: .allowFragments) { response in
if let e = response.result.error {
callback(response.request, response.response, Result.failure(e))
} else {
callback(response.request, response.response, Result.success(JSON(rawValue: response.result.value!)!.arrayValue.map { T(json: $0) }))
}
}
}
public enum Router {
/* connect */
// case Connect
/* users */
case users(String)
case user(String)
case tracksOfUser(SoundCloudKit.User)
case playlistsOfUser(SoundCloudKit.User)
case followingsOfUser(SoundCloudKit.User)
// case FollowersOfUser(SoundCloudKit.User)
// case CommentsOfUser(SoundCloudKit.User)
case favoritesOfUser(SoundCloudKit.User)
// case GroupsOfUser(SoundCloudKit.User)
// case WebProfilesOfUser(SoundCloudKit.User)
/* tracks */
case track(String)
// case CommentsOfTrack(SoundCloudKit.Track)
// case CommentOfTrack(SoundCloudKit.Track, SoundCloudKit.Comment)
// case FavoritersOfTrack(SoundCloudKit.Track)
// case FavoriterOfTrack(SoundCloudKit.Track, SoundCloudKit.User)
// case SecretTokenOfTrack(SoundCloudKit.Track)
/* playlists */
case playlist(String)
// case SecretTokenOfPlaylist(SoundCloudKit.Playlist)
/* groups */
/* comments */
/* me */
case me
/* me/connections */
/* me/activities */
case activities
case nextActivities(String)
case futureActivities(String)
/* apps */
/* resolve */
/* oembed */
var method: Alamofire.HTTPMethod {
switch self {
case .users: return .get
case .user: return .get
case .tracksOfUser: return .get
case .playlistsOfUser: return .get
case .followingsOfUser: return .get
case .favoritesOfUser: return .get
case .track: return .get
case .playlist: return .get
case .me: return .get
case .activities: return .get
case .nextActivities: return .get
case .futureActivities: return .get
}
}
var path: String {
switch self {
case .users(_): return "/users"
case .user(let userId): return "/users/\(userId)"
case .tracksOfUser(let user): return "/users/\(user.id)/tracks"
case .playlistsOfUser(let user): return "/users/\(user.id)/playlists"
case .followingsOfUser(let user): return "/users/\(user.id)/followings"
case .favoritesOfUser(let user): return "/users/\(user.id)/favorites"
case .track(let trackId): return "/tracks/\(trackId)"
case .playlist(let playlistId): return "/playlists/\(playlistId)"
case .me: return "/me"
case .activities: return "/me/activities"
case .nextActivities(_): return ""
case .futureActivities(_): return ""
}
}
var url: URL {
switch self {
case .nextActivities(let href): return URL(string: href)!
case .futureActivities(let href): return URL(string: href)!
default: return URL(string: APIClient.baseURLString + path)!
}
}
var params: [String: AnyObject] {
switch self {
case .users(let q): return ["q": q as AnyObject]
case .user(_): return [:]
case .tracksOfUser(_): return [:]
case .playlistsOfUser(_): return [:]
case .followingsOfUser(_): return [:]
case .favoritesOfUser(_): return [:]
case .track(_): return [:]
case .playlist(_): return [:]
case .me: return [:]
case .activities: return [:]
case .nextActivities(_): return [:]
case .futureActivities(_): return [:]
}
}
var needsOAuthToken: Bool {
switch self {
case .users(_): return false
case .user(_): return false
case .tracksOfUser(_): return false
case .playlistsOfUser(_): return false
case .followingsOfUser(_): return false
case .favoritesOfUser(_): return false
case .track(_): return false
case .playlist(_): return false
case .me: return true
case .activities: return true
case .nextActivities(_): return true
case .futureActivities(_): return true
}
}
}
}
internal struct RouterRequest: URLRequestConvertible {
var router: APIClient.Router
var client: APIClient
public func asURLRequest() throws -> URLRequest {
var req = URLRequest(url: router.url)
req.httpMethod = router.method.rawValue
var params = router.params
params["client_id"] = client.clientId as AnyObject?
if let token = client.accessToken, router.needsOAuthToken {
params["oauth_token"] = token as AnyObject?
}
return try URLEncoding.default.encode(req, with: params)
}
}
| mit | 57ac555ade174bffd5516917f54a2c5c | 39.847368 | 154 | 0.563587 | 4.912025 | false | false | false | false |
JKapanke/worldvisitor | WorldVisitor/CountryViewController.swift | 1 | 3441 | //
// CountryViewController.swift
// WorldTraveler
//
// Created by Jason Kapanke on 12/7/14.
// Copyright (c) 2014 Better Things. All rights reserved.
//
import UIKit
class CountryViewController: UIViewController
{
@IBOutlet weak var typeOfCountry: AnyObject!
@IBOutlet weak var dynamicLabel: UILabel!
@IBOutlet weak var dynamicMap: UIImageView!
@IBOutlet weak var dynamicActivityOne: UILabel!
@IBOutlet weak var dynamicActivityTwo: UILabel!
@IBOutlet weak var dynamicActivityThree: UILabel!
@IBOutlet var swipeRightGestureRecog: UISwipeGestureRecognizer!
@IBOutlet var swipeLeftGestureRecog: UISwipeGestureRecognizer!
@IBOutlet var swipeDownGestureRecog: UISwipeGestureRecognizer!
var selectedActivity: Activity!
override func viewDidLoad()
{
super.viewDidLoad()
var currentCountry = typeOfCountry as Country
println("The country name is: \(currentCountry.getCountryName())")
//change the label to the passed data
dynamicLabel.text = currentCountry.getCountryName()
//set the image in the View
dynamicMap.image = currentCountry.getMapImage()
//set the activities
dynamicActivityOne.text = "Swipe Right to " + currentCountry.getFirstActivity().getActivityName()
dynamicActivityTwo.text = "Swipe Left to " + currentCountry.getSecondActivity().getActivityName()
dynamicActivityThree.text = "Swipe Down to " + currentCountry.getThirdActivity().getActivityName()
swipeRightGestureRecog.addTarget(self, action: "swipedRightAction")
swipeLeftGestureRecog.addTarget(self, action: "swipedLeftAction")
swipeDownGestureRecog.addTarget(self, action: "swipedDownAction")
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// prepare for seque
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
//the segue must be named as noted in the operator
if (segue.identifier == "toActivitySegueFromSwipeRight")
{
swipedRightAction()
var cvc = segue.destinationViewController as ActivityViewController;
cvc.incomingActivitySelected = selectedActivity
}
else if (segue.identifier == "toActivitySegueFromSwipeLeft")
{
swipedLeftAction()
var cvc = segue.destinationViewController as ActivityViewController;
cvc.incomingActivitySelected = selectedActivity
}
else if (segue.identifier == "toActivitySegueFromSwipeDown")
{
swipedDownAction()
var cvc = segue.destinationViewController as ActivityViewController;
cvc.incomingActivitySelected = selectedActivity
}
else
{
var cvc = segue.destinationViewController as ActivityViewController;
cvc.incomingActivitySelected = Activity()
}
}
func swipedRightAction()
{
selectedActivity = (typeOfCountry as Country).getFirstActivity()
}
func swipedLeftAction()
{
selectedActivity = (typeOfCountry as Country).getSecondActivity()
}
func swipedDownAction()
{
selectedActivity = (typeOfCountry as Country).getThirdActivity()
}
}
| gpl-2.0 | 7ba636a46d1c81fd978b966c1a997b7b | 33.41 | 106 | 0.673932 | 5.285714 | false | false | false | false |
mogol/flutter_secure_storage | flutter_secure_storage/ios/Classes/FlutterSecureStorage.swift | 1 | 5751 | //
// FlutterSecureStorageManager.swift
// flutter_secure_storage
//
// Created by Julian Steenbakker on 22/08/2022.
//
import Foundation
class FlutterSecureStorage{
private func baseQuery(key: String?, groupId: String?, accountName: String?, synchronizable: Bool?, returnData: Bool?) -> Dictionary<CFString, Any> {
var keychainQuery: [CFString: Any] = [kSecClass : kSecClassGenericPassword]
if (key != nil) {
keychainQuery[kSecAttrAccount] = key
}
if (groupId != nil) {
keychainQuery[kSecAttrAccessGroup] = groupId
}
if (accountName != nil) {
keychainQuery[kSecAttrService] = accountName
}
if (synchronizable != nil) {
keychainQuery[kSecAttrSynchronizable] = synchronizable
}
if (returnData != nil) {
keychainQuery[kSecReturnData] = returnData
}
return keychainQuery
}
internal func containsKey(key: String, groupId: String?, accountName: String?, synchronizable: Bool?) -> Bool {
if read(key: key, groupId: groupId, accountName: accountName, synchronizable: synchronizable).value != nil {
return true
} else {
return false
}
}
internal func readAll(groupId: String?, accountName: String?, synchronizable: Bool?) -> FlutterSecureStorageResponse {
var keychainQuery = baseQuery(key: nil, groupId: groupId, accountName: accountName, synchronizable: synchronizable, returnData: true)
keychainQuery[kSecMatchLimit] = kSecMatchLimitAll
keychainQuery[kSecReturnAttributes] = true
var ref: AnyObject?
let status = SecItemCopyMatching(
keychainQuery as CFDictionary,
&ref
)
var results: [String: String] = [:]
if (status == noErr) {
(ref as! NSArray).forEach { item in
let key: String = (item as! NSDictionary)[kSecAttrAccount] as! String
let value: String = String(data: (item as! NSDictionary)[kSecValueData] as! Data, encoding: .utf8) ?? ""
results[key] = value
}
}
return FlutterSecureStorageResponse(status: status, value: results)
}
internal func read(key: String, groupId: String?, accountName: String?, synchronizable: Bool?) -> FlutterSecureStorageResponse {
let keychainQuery = baseQuery(key: key, groupId: groupId, accountName: accountName, synchronizable: synchronizable, returnData: true)
var ref: AnyObject?
let status = SecItemCopyMatching(
keychainQuery as CFDictionary,
&ref
)
var value: String? = nil
if (status == noErr) {
value = String(data: ref as! Data, encoding: .utf8)
}
return FlutterSecureStorageResponse(status: status, value: value)
}
internal func deleteAll(groupId: String?, accountName: String?, synchronizable: Bool?) -> OSStatus {
let keychainQuery = baseQuery(key: nil, groupId: groupId, accountName: accountName, synchronizable: synchronizable, returnData: nil)
return SecItemDelete(keychainQuery as CFDictionary)
}
internal func delete(key: String, groupId: String?, accountName: String?, synchronizable: Bool?) -> OSStatus {
let keychainQuery = baseQuery(key: key, groupId: groupId, accountName: accountName, synchronizable: synchronizable, returnData: true)
return SecItemDelete(keychainQuery as CFDictionary)
}
internal func write(key: String, value: String, groupId: String?, accountName: String?, synchronizable: Bool?, accessibility: String?) -> OSStatus {
var attrAccessible: CFString = kSecAttrAccessibleWhenUnlocked
if (accessibility != nil) {
switch accessibility {
case "passcode":
attrAccessible = kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
break;
case "unlocked":
attrAccessible = kSecAttrAccessibleWhenUnlocked
break
case "unlocked_this_device":
attrAccessible = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
break
case "first_unlock":
attrAccessible = kSecAttrAccessibleAfterFirstUnlock
break
case "first_unlock_this_device":
attrAccessible = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
break
default:
attrAccessible = kSecAttrAccessibleWhenUnlocked
}
}
let keyExists = containsKey(key: key, groupId: groupId, accountName: accountName, synchronizable: synchronizable)
var keychainQuery = baseQuery(key: key, groupId: groupId, accountName: accountName, synchronizable: synchronizable, returnData: nil)
if (keyExists) {
let update: [CFString: Any?] = [
kSecValueData: value.data(using: String.Encoding.utf8),
kSecAttrAccessible: attrAccessible,
kSecAttrSynchronizable: synchronizable
]
return SecItemUpdate(keychainQuery as CFDictionary, update as CFDictionary)
} else {
keychainQuery[kSecValueData] = value.data(using: String.Encoding.utf8)
keychainQuery[kSecAttrAccessible] = attrAccessible
return SecItemAdd(keychainQuery as CFDictionary, nil)
}
}
struct FlutterSecureStorageResponse {
var status: OSStatus?
var value: Any?
}
}
| bsd-3-clause | 4098cedbe6076d5a9f1a02a35d8f8d81 | 38.390411 | 153 | 0.614502 | 5.751 | false | false | false | false |
godenzim/NetKit | NetKit/Common/JSON/JSON.swift | 1 | 9540 | //
// JSON.swift
// TurboKit
//
// Created by Mike Godenzi on 12.05.15.
// Copyright (c) 2015 Mike Godenzi. All rights reserved.
//
import Foundation
public protocol JSONConvertible {
func toJSON() -> JSON
}
public protocol JSONInitializable {
init?(_ json : JSON)
}
public enum JSON : Equatable {
case Array([JSON])
case Object([Swift.String:JSON])
case String(Swift.String)
case Integer(Int)
case Real(Double)
case Boolean(Bool)
case Null
public init(_ obj : JSONConvertible) {
self = obj.toJSON()
}
public init(data : NSData) throws {
if let obj = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? JSONConvertible {
self = obj.toJSON()
} else {
throw NSError(domain: "JSON", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unknown error"])
}
}
public func value<T>() -> T? {
switch self {
case let .String(v as T):
return v
case let .Array(v as T):
return v
case let .Object(v as T):
return v
case let .Integer(v as T):
return v
case let .Real(v as T):
return v
case let .Boolean(v as T):
return v
default:
return nil
}
}
public subscript(key : Swift.String) -> JSON {
get {
if let d : [Swift.String:JSON] = value() {
return d[key] ?? .Null
}
return .Null
}
}
public subscript(index : Int) -> JSON {
get {
if let a : [JSON] = value() {
return index < a.count ? a[index] : .Null
}
return .Null
}
}
}
extension JSON : StringLiteralConvertible {
public typealias ExtendedGraphemeClusterLiteralType = Swift.String
public typealias UnicodeScalarLiteralType = Swift.String
public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
self = .String(value)
}
public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self = .String(value)
}
public init(stringLiteral value: StringLiteralType) {
self = .String(value)
}
}
extension JSON : ArrayLiteralConvertible {
public typealias Element = JSON
public init(arrayLiteral elements: Element...) {
self = .Array(elements)
}
}
extension JSON : DictionaryLiteralConvertible {
public typealias Key = Swift.String
public typealias Value = JSON
public init(dictionaryLiteral elements: (Key, Value)...) {
var dictionary : [Key:Value] = [Key:Value]()
for (key, value) in elements {
dictionary[key] = value
}
self = .Object(dictionary)
}
init(_ dictionary : [Key:Value]) {
self = .Object(dictionary)
}
}
extension JSON : IntegerLiteralConvertible {
public init(integerLiteral value: IntegerLiteralType) {
self = .Integer(value)
}
}
extension JSON : FloatLiteralConvertible {
public init(floatLiteral value: FloatLiteralType) {
self = .Real(value)
}
}
extension JSON : BooleanLiteralConvertible {
public init(booleanLiteral value: BooleanLiteralType) {
self = .Boolean(value)
}
}
extension JSON : NilLiteralConvertible {
public init(nilLiteral: ()) {
self = .Null
}
}
extension JSON : SequenceType {
public func generate() -> AnyGenerator<(Swift.String,JSON)> {
switch self {
case let .Array(v):
var nextIndex = 0
return anyGenerator {
if nextIndex < v.count {
return ("\(nextIndex)", v[nextIndex++])
}
return nil
}
case let .Object(v):
var nextIndex = v.startIndex
return anyGenerator {
if nextIndex < v.endIndex {
return v[nextIndex++]
}
return nil
}
default:
return anyGenerator {return nil}
}
}
}
extension JSON : CustomStringConvertible {
public var description : Swift.String {
switch self {
case let .String(v):
return v
case let .Array(v):
return v.description
case let .Object(v):
return v.description
case let .Integer(v):
return v.description
case let .Real(v):
return v.description
case let .Boolean(v):
return v.description
default:
return "Null"
}
}
}
extension JSON : CustomDebugStringConvertible {
public var debugDescription : Swift.String {
switch self {
case let .String(v):
return "String(\(v))"
case let .Array(v):
return "Array(\(v.debugDescription))"
case let .Object(v):
return "Object(\(v.debugDescription))"
case let .Integer(v):
return "Integer(\(v.description))"
case let .Real(v):
return "Real(\(v.description))"
case let .Boolean(v):
return "Boolean(\(v.description))"
default:
return "Null"
}
}
}
extension JSON {
public func map<T>(block : (JSON) -> T?) -> [T]? {
var result = [T]()
for (_, v) in self {
if let t = block(v) {
result.append(t)
}
}
return result.count > 0 ? result : nil
}
}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs, rhs) {
case let (.Object(v1), .Object(v2)):
return v1 == v2
case let (.Array(v1), .Array(v2)):
return v1 == v2
case let (.String(v1), .String(v2)):
return v1 == v2
case let (.Integer(v1), .Integer(v2)):
return v1 == v2
case let (.Real(v1), .Real(v2)):
return v1 == v2
case let (.Boolean(v1), .Boolean(v2)):
return v1 == v2
case (.Null, .Null):
return true
default:
return false
}
}
extension Int : JSONConvertible, JSONInitializable {
public init?(_ json : JSON) {
if let i : Int = json.value() {
self = i
} else {
return nil
}
}
public func toJSON() -> JSON {
return .Integer(self)
}
}
extension Double : JSONConvertible, JSONInitializable {
public init?(_ json : JSON) {
if let d : Double = json.value() {
self = d
} else {
return nil
}
}
public func toJSON() -> JSON {
return .Real(self)
}
}
extension Float : JSONInitializable {
public init?(_ json: JSON) {
if let d : Double = json.value() {
self = Float(d)
} else {
return nil
}
}
}
extension Bool : JSONConvertible, JSONInitializable {
public init?(_ json : JSON) {
if let b : Bool = json.value() {
self = b
} else {
return nil
}
}
public func toJSON() -> JSON {
return .Boolean(self)
}
}
extension NSNumber : JSONConvertible {
public func toJSON() -> JSON {
let type = String.fromCString(self.objCType)!
switch type {
case "f", "d":
return .Real(self.doubleValue)
case "c":
return .Boolean(self.boolValue)
default:
return .Integer(self.integerValue)
}
}
}
extension Array : JSONConvertible {
public func toJSON() -> JSON {
let jsonArray : [JSON] = self.map { element in
if let jc = element as? JSONConvertible {
return jc.toJSON()
}
return .Null
}
return .Array(jsonArray)
}
}
extension NSArray : JSONConvertible {
public func toJSON() -> JSON {
var jsonArray = [JSON]()
jsonArray.reserveCapacity(self.count)
for e in self {
if let jc = e as? JSONConvertible {
jsonArray.append(jc.toJSON())
} else {
jsonArray.append(.Null)
}
}
return .Array(jsonArray)
}
}
extension Dictionary : JSONConvertible {
public func toJSON() -> JSON {
var jsonDictionary = [String:JSON]()
for (key, value) in self {
if let s = key as? String {
if let j = value as? JSONConvertible {
jsonDictionary[s] = j.toJSON()
} else {
jsonDictionary[s] = .Null
}
}
}
return .Object(jsonDictionary)
}
}
extension NSDictionary : JSONConvertible {
public func toJSON() -> JSON {
var jsonDictionary = [String:JSON]()
for (key, value) in self {
if let s = key as? String {
if let j = value as? JSONConvertible {
jsonDictionary[s] = j.toJSON()
} else {
jsonDictionary[s] = .Null
}
}
}
return .Object(jsonDictionary)
}
}
extension String : JSONConvertible, JSONInitializable {
public init?(_ json : JSON) {
if let v : String = json.value() {
self = v
} else {
return nil
}
}
public func toJSON() -> JSON {
return .String(self)
}
}
extension NSString : JSONConvertible {
public func toJSON() -> JSON {
return .String(String(self))
}
}
prefix operator <? {}
prefix operator <! {}
public prefix func <? <T : JSONInitializable> (json : JSON) -> T? {
return T(json)
}
public prefix func <! <T : JSONInitializable> (json : JSON) -> T {
return (<?json)!
}
public prefix func <? <T : JSONInitializable> (json : JSON) -> [T]? {
if let jsonArray : [JSON] = json.value() {
var result = [T]()
result.reserveCapacity(jsonArray.count)
for value in jsonArray {
if let e : T = <?value {
result.append(e)
}
}
return result.count > 0 ? result : nil
}
return nil
}
public prefix func <! <T : JSONInitializable> (json : JSON) -> [T] {
let result : [T]? = <?json
return result!
}
public prefix func <? <T : JSONInitializable> (json : JSON) -> [String:T]? {
if let jsonDict : [String:JSON] = json.value() {
var result = [String:T](minimumCapacity: jsonDict.count)
for (k, v) in jsonDict {
if let value : T = <?v {
result[k] = value
} else {
return nil
}
}
return result
}
return nil
}
public prefix func <! <T : JSONInitializable> (json : JSON) -> [String:T] {
let result : [String:T]? = <?json
return result!
}
public class JSONDataParser : DataParser {
public typealias ResultType = JSON
required public init() {}
public func parseData(data: NSData) throws -> ResultType {
if let j = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? JSONConvertible {
return JSON(j)
} else {
throw NSError(domain: "JSONDataParser", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unknown error"])
}
}
}
public class JSONResponseParser : HTTPResponseParser<JSONDataParser> {
public override init() {
super.init()
acceptedMIMETypes = ["application/json", "text/javascript"]
}
}
| mit | d76db16bc28cdfec07fd301bd2d3e436 | 18.670103 | 118 | 0.646751 | 3.252642 | false | false | false | false |
ul7290/realm-cocoa | RealmSwift-swift1.2/Tests/ObjectSchemaInitializationTests.swift | 3 | 9871 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// 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 XCTest
import RealmSwift
import Realm.Private
import Realm.Dynamic
import Foundation
class ObjectSchemaInitializationTests: TestCase {
func testAllValidTypes() {
let object = SwiftObject()
let objectSchema = object.objectSchema
let noSuchCol = objectSchema["noSuchCol"]
XCTAssertNil(noSuchCol)
let boolCol = objectSchema["boolCol"]
XCTAssertNotNil(boolCol)
XCTAssertEqual(boolCol!.name, "boolCol")
XCTAssertEqual(boolCol!.type, PropertyType.Bool)
XCTAssertFalse(boolCol!.indexed)
XCTAssertFalse(boolCol!.optional)
XCTAssertNil(boolCol!.objectClassName)
let intCol = objectSchema["intCol"]
XCTAssertNotNil(intCol)
XCTAssertEqual(intCol!.name, "intCol")
XCTAssertEqual(intCol!.type, PropertyType.Int)
XCTAssertFalse(intCol!.indexed)
XCTAssertFalse(intCol!.optional)
XCTAssertNil(intCol!.objectClassName)
let floatCol = objectSchema["floatCol"]
XCTAssertNotNil(floatCol)
XCTAssertEqual(floatCol!.name, "floatCol")
XCTAssertEqual(floatCol!.type, PropertyType.Float)
XCTAssertFalse(floatCol!.indexed)
XCTAssertFalse(floatCol!.optional)
XCTAssertNil(floatCol!.objectClassName)
let doubleCol = objectSchema["doubleCol"]
XCTAssertNotNil(doubleCol)
XCTAssertEqual(doubleCol!.name, "doubleCol")
XCTAssertEqual(doubleCol!.type, PropertyType.Double)
XCTAssertFalse(doubleCol!.indexed)
XCTAssertFalse(doubleCol!.optional)
XCTAssertNil(doubleCol!.objectClassName)
let stringCol = objectSchema["stringCol"]
XCTAssertNotNil(stringCol)
XCTAssertEqual(stringCol!.name, "stringCol")
XCTAssertEqual(stringCol!.type, PropertyType.String)
XCTAssertFalse(stringCol!.indexed)
XCTAssertFalse(stringCol!.optional)
XCTAssertNil(stringCol!.objectClassName)
let binaryCol = objectSchema["binaryCol"]
XCTAssertNotNil(binaryCol)
XCTAssertEqual(binaryCol!.name, "binaryCol")
XCTAssertEqual(binaryCol!.type, PropertyType.Data)
XCTAssertFalse(binaryCol!.indexed)
XCTAssertFalse(binaryCol!.optional)
XCTAssertNil(binaryCol!.objectClassName)
let dateCol = objectSchema["dateCol"]
XCTAssertNotNil(dateCol)
XCTAssertEqual(dateCol!.name, "dateCol")
XCTAssertEqual(dateCol!.type, PropertyType.Date)
XCTAssertFalse(dateCol!.indexed)
XCTAssertFalse(dateCol!.optional)
XCTAssertNil(dateCol!.objectClassName)
let objectCol = objectSchema["objectCol"]
XCTAssertNotNil(objectCol)
XCTAssertEqual(objectCol!.name, "objectCol")
XCTAssertEqual(objectCol!.type, PropertyType.Object)
XCTAssertFalse(objectCol!.indexed)
XCTAssertTrue(objectCol!.optional)
XCTAssertEqual(objectCol!.objectClassName!, "SwiftBoolObject")
let arrayCol = objectSchema["arrayCol"]
XCTAssertNotNil(arrayCol)
XCTAssertEqual(arrayCol!.name, "arrayCol")
XCTAssertEqual(arrayCol!.type, PropertyType.Array)
XCTAssertFalse(arrayCol!.indexed)
XCTAssertFalse(arrayCol!.optional)
XCTAssertEqual(objectCol!.objectClassName!, "SwiftBoolObject")
let dynamicArrayCol = SwiftCompanyObject().objectSchema["employees"]
XCTAssertNotNil(dynamicArrayCol)
XCTAssertEqual(dynamicArrayCol!.name, "employees")
XCTAssertEqual(dynamicArrayCol!.type, PropertyType.Array)
XCTAssertFalse(dynamicArrayCol!.indexed)
XCTAssertFalse(arrayCol!.optional)
XCTAssertEqual(dynamicArrayCol!.objectClassName!, "SwiftEmployeeObject")
}
func testInvalidObjects() {
let schema = RLMObjectSchema(forObjectClass: SwiftFakeObjectSubclass.self) // Should be able to get a schema for a non-RLMObjectBase subclass
XCTAssertEqual(schema.properties.count, 1)
// FIXME - disable any and make sure this fails
RLMObjectSchema(forObjectClass: SwiftObjectWithAnyObject.self) // Should throw when not ignoring a property of a type we can't persist
RLMObjectSchema(forObjectClass: SwiftObjectWithEnum.self) // Shouldn't throw when not ignoring a property of a type we can't persist if it's not dynamic
RLMObjectSchema(forObjectClass: SwiftObjectWithStruct.self) // Shouldn't throw when not ignoring a property of a type we can't persist if it's not dynamic
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithDatePrimaryKey.self), "Should throw when setting a non int/string primary key")
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithNSURL.self), "Should throw when not ignoring a property of a type we can't persist")
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithNonOptionalLinkProperty.self), "Should throw when not marking a link property as optional")
}
func testPrimaryKey() {
XCTAssertNil(SwiftObject().objectSchema.primaryKeyProperty, "Object should default to having no primary key property")
XCTAssertEqual(SwiftPrimaryStringObject().objectSchema.primaryKeyProperty!.name, "stringCol")
}
func testIgnoredProperties() {
let schema = SwiftIgnoredPropertiesObject().objectSchema
XCTAssertNil(schema["runtimeProperty"], "The object schema shouldn't contain ignored properties")
XCTAssertNil(schema["runtimeDefaultProperty"], "The object schema shouldn't contain ignored properties")
XCTAssertNil(schema["readOnlyProperty"], "The object schema shouldn't contain read-only properties")
}
func testIndexedProperties() {
XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["stringCol"]!.indexed)
let unindexibleSchema = RLMObjectSchema(forObjectClass: SwiftObjectWithUnindexibleProperties.self)
for propName in SwiftObjectWithUnindexibleProperties.indexedProperties() {
XCTAssertFalse(unindexibleSchema[propName]!.indexed, "Shouldn't mark unindexible property '\(propName)' as indexed")
}
}
func testOptionalProperties() {
let schema = RLMObjectSchema(forObjectClass: SwiftOptionalObject.self)
for prop in schema.properties {
XCTAssertTrue((prop as! RLMProperty).optional)
}
let types = Set(map(schema.properties) { prop in
(prop as! RLMProperty).type
})
XCTAssertEqual(types, Set([.String, .String, .Data, .Date, .Object, .Int, .Float, .Double, .Bool]))
}
func testImplicitlyUnwrappedOptionalsAreParsedAsOptionals() {
let schema = SwiftImplicitlyUnwrappedOptionalObject().objectSchema
XCTAssertTrue(schema["optObjectCol"]!.optional)
XCTAssertTrue(schema["optNSStringCol"]!.optional)
XCTAssertTrue(schema["optStringCol"]!.optional)
XCTAssertTrue(schema["optBinaryCol"]!.optional)
XCTAssertTrue(schema["optDateCol"]!.optional)
}
func testNonRealmOptionalTypesDeclaredAsRealmOptional() {
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithNonRealmOptionalType.self))
}
}
class SwiftFakeObject : NSObject {
dynamic class func primaryKey() -> String! { return nil }
dynamic class func ignoredProperties() -> [String] { return [] }
dynamic class func indexedProperties() -> [String] { return [] }
}
class SwiftObjectWithNSURL: SwiftFakeObject {
dynamic var URL = NSURL(string: "http://realm.io")!
}
class SwiftObjectWithAnyObject: SwiftFakeObject {
dynamic var anyObject: AnyObject = NSString(string: "")
}
enum SwiftEnum {
case Case1
case Case2
}
class SwiftObjectWithEnum: SwiftFakeObject {
var swiftEnum = SwiftEnum.Case1
}
class SwiftObjectWithStruct: SwiftFakeObject {
var swiftStruct = SortDescriptor(property: "prop")
}
class SwiftObjectWithDatePrimaryKey: SwiftFakeObject {
dynamic var date = NSDate()
dynamic override class func primaryKey() -> String! {
return "date"
}
}
class SwiftFakeObjectSubclass: SwiftFakeObject {
dynamic var dateCol = NSDate()
}
class SwiftObjectWithUnindexibleProperties: SwiftFakeObject {
dynamic var boolCol = false
dynamic var intCol = 123
dynamic var floatCol = 1.23 as Float
dynamic var doubleCol = 12.3
dynamic var binaryCol = "a".dataUsingEncoding(NSUTF8StringEncoding)!
dynamic var dateCol = NSDate(timeIntervalSince1970: 1)
dynamic var objectCol: SwiftBoolObject? = SwiftBoolObject()
let arrayCol = List<SwiftBoolObject>()
dynamic override class func indexedProperties() -> [String] {
return ["boolCol", "intCol", "floatCol", "doubleCol", "binaryCol", "dateCol", "objectCol", "arrayCol"]
}
}
class SwiftObjectWithNonNullableOptionalProperties: SwiftFakeObject {
dynamic var optDateCol: NSDate?
}
class SwiftObjectWithNonOptionalLinkProperty: SwiftFakeObject {
dynamic var objectCol = SwiftBoolObject()
}
extension Set: RealmOptionalType { }
class SwiftObjectWithNonRealmOptionalType: SwiftFakeObject {
let set = RealmOptional<Set<Int>>()
}
| apache-2.0 | b16074294c40a4e666b14902fa987390 | 39.454918 | 166 | 0.708439 | 5.261727 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/iterator-for-combination.swift | 2 | 2661 | /**
* https://leetcode.com/problems/iterator-for-combination/
*
*
*/
// Date: Thu Aug 13 14:09:59 PDT 2020
/// - Complexity:
/// - Time: O(2^combinationLength * characters.count + nlogn), n is the number of candidates.
/// - Space: O(n), n is the number of candidates.
///
class CombinationIterator {
let candidate: [String]
var current: Int
init(_ characters: String, _ combinationLength: Int) {
self.current = -1
let text = Array(characters)
var cand: [String] = []
for mask in 1 ..< (1 << text.count) {
var result = ""
var count = 0
for index in 0 ..< text.count {
if ((1 << index) & mask) > 0 {
result += String(text[index])
count += 1
}
}
if count == combinationLength {
cand.append(result)
}
}
self.candidate = Array(cand).sorted()
print(self.candidate)
}
func next() -> String {
current += 1
return self.candidate[current]
}
func hasNext() -> Bool {
return current + 1 < candidate.count
}
}
/**
* Your CombinationIterator object will be instantiated and called as such:
* let obj = CombinationIterator(characters, combinationLength)
* let ret_1: String = obj.next()
* let ret_2: Bool = obj.hasNext()
*/
/// Each state will be presented as a tuple as (current index, steps left).
/// So the number of V, known as |V|, is C(characters.count, combinationLength)
///
/// - Complexity:
/// - Time: O(|V|), |V| is number of state.
/// - Space: O(k), k is combinationLength.
///
class CombinationIterator {
var candidate: [String]
init(_ characters: String, _ combinationLength: Int) {
self.candidate = []
self.dfs(Array(characters), at: 0, "", combinationLength)
}
private func dfs(_ characters: [Character], at start: Int, _ result: String, _ stepsLeft: Int) {
if stepsLeft <= 0 {
self.candidate.append(result)
return
}
for index in start ... (characters.count - stepsLeft) {
self.dfs(characters, at: index + 1, result + String(characters[index]), stepsLeft - 1)
}
}
func next() -> String {
return self.candidate.removeFirst()
}
func hasNext() -> Bool {
return self.candidate.isEmpty == false
}
}
/**
* Your CombinationIterator object will be instantiated and called as such:
* let obj = CombinationIterator(characters, combinationLength)
* let ret_1: String = obj.next()
* let ret_2: Bool = obj.hasNext()
*/
| mit | 46231a439a238ea08d4e4d6d8cfb4f2a | 28.241758 | 100 | 0.569335 | 3.942222 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.