repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
devpunk/punknote
punknote/Controller/Home/CHome.swift
1
3068
import UIKit class CHome:Controller<VHome> { let model:MHome override init() { model = MHome() super.init() } required init?(coder:NSCoder) { return nil } override func viewDidLoad() { super.viewDidLoad() MSession.sharedInstance.loadSession() } override func viewDidAppear(_ animated:Bool) { super.viewDidAppear(animated) model.reload(controller:self) } private func confirmDelete(item:MHomeItem) { model.deleteNote(controller:self, item:item) } //MARK: public func newNote() { editNote(item:nil) } func notesLoaded() { DispatchQueue.main.async { [weak self] in guard let view:VHome = self?.view as? VHome else { return } view.stopLoading() } } func deleteNote(item:MHomeItem) { let alert:UIAlertController = UIAlertController( title:NSLocalizedString("CHome_deleteAlertTitle", comment:""), message:nil, preferredStyle:UIAlertControllerStyle.actionSheet) let actionCancel:UIAlertAction = UIAlertAction( title: NSLocalizedString("CHome_deleteAlertCancel", comment:""), style: UIAlertActionStyle.cancel) let actionDelete:UIAlertAction = UIAlertAction( title: NSLocalizedString("CHome_deleteAlertDelete", comment:""), style: UIAlertActionStyle.destructive) { [weak self] (action:UIAlertAction) in self?.confirmDelete(item:item) } alert.addAction(actionDelete) alert.addAction(actionCancel) if let popover:UIPopoverPresentationController = alert.popoverPresentationController { popover.sourceView = view popover.sourceRect = CGRect.zero popover.permittedArrowDirections = UIPopoverArrowDirection.up } present(alert, animated:true, completion:nil) } func editNote(item:MHomeItem?) { guard let parent:ControllerParent = self.parent as? ControllerParent else { return } let controller:CCreate = CCreate(modelHomeItem:item) parent.push( controller:controller, horizontal:ControllerParent.Horizontal.right) } func shareNote(item:MHomeItem) { guard let parent:ControllerParent = self.parent as? ControllerParent else { return } let controller:CShare = CShare(modelHomeItem:item) parent.push( controller:controller, horizontal:ControllerParent.Horizontal.right) } }
mit
dsoisson/SwiftLearningExercises
SwiftLearning.playground/Pages/Closures.xcplaygroundpage/Contents.swift
1
373
/*: [Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next) */ /*: # Closures */ import Foundation /*: **Supporting Chapters:** - [Closures](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html) */ /*: [Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next) */
mit
tkremenek/swift
validation-test/stdlib/Slice/Slice_Of_MinimalMutableRangeReplaceableCollection_WithPrefixAndSuffix.swift
21
3822
// -*- swift -*- //===----------------------------------------------------------------------===// // Automatically Generated From validation-test/stdlib/Slice/Inputs/Template.swift.gyb // Do Not Edit Directly! //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // FIXME: the test is too slow when the standard library is not optimized. // REQUIRES: optimized_stdlib import StdlibUnittest import StdlibCollectionUnittest var SliceTests = TestSuite("Collection") let prefix: [Int] = [-9999, -9998, -9997, -9996, -9995] let suffix: [Int] = [] func makeCollection(elements: [OpaqueValue<Int>]) -> Slice<MinimalMutableRangeReplaceableCollection<OpaqueValue<Int>>> { var baseElements = prefix.map(OpaqueValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(OpaqueValue.init)) let base = MinimalMutableRangeReplaceableCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: prefix.count) let endIndex = base.index( base.startIndex, offsetBy: prefix.count + elements.count) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfEquatable(elements: [MinimalEquatableValue]) -> Slice<MinimalMutableRangeReplaceableCollection<MinimalEquatableValue>> { var baseElements = prefix.map(MinimalEquatableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalEquatableValue.init)) let base = MinimalMutableRangeReplaceableCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: prefix.count) let endIndex = base.index( base.startIndex, offsetBy: prefix.count + elements.count) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfComparable(elements: [MinimalComparableValue]) -> Slice<MinimalMutableRangeReplaceableCollection<MinimalComparableValue>> { var baseElements = prefix.map(MinimalComparableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalComparableValue.init)) let base = MinimalMutableRangeReplaceableCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: prefix.count) let endIndex = base.index( base.startIndex, offsetBy: prefix.count + elements.count) return Slice(base: base, bounds: startIndex..<endIndex) } var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior = .trap SliceTests.addRangeReplaceableSliceTests( "Slice_Of_MinimalMutableRangeReplaceableCollection_WithPrefixAndSuffix.swift.", makeCollection: makeCollection, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: 6 ) SliceTests.addMutableCollectionTests( "Slice_Of_MinimalMutableRangeReplaceableCollection_WithPrefixAndSuffix.swift.", makeCollection: makeCollection, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, makeCollectionOfComparable: makeCollectionOfComparable, wrapValueIntoComparable: identityComp, extractValueFromComparable: identityComp, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: 6 , withUnsafeMutableBufferPointerIsSupported: false, isFixedLengthCollection: true ) runAllTests()
apache-2.0
parkboo/ios-charts
Charts/Classes/Interfaces/CubicLineChartDataProvider.swift
1
533
// // LineChartDataProvider.swift // Charts // // Created by Daniel Cohen Gindi on 27/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics @objc public protocol CubicLineChartDataProvider: BarLineScatterCandleBubbleChartDataProvider { var cubicData: CubicLineChartData? { get } func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis }
apache-2.0
tkremenek/swift
test/Profiler/coverage_private.swift
22
504
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -profile-generate -profile-coverage-mapping -emit-sorted-sil -emit-sil -module-name coverage_private %s | %FileCheck %s // RUN: %target-swift-frontend -profile-generate -profile-coverage-mapping -emit-ir %s struct S { func visible() { hidden() } // CHECK-LABEL: sil_coverage_map {{.*}}// coverage_private.S.(hidden in {{.*}})() -> () // CHECK-NEXT: [[@LINE+1]]:25 -> [[@LINE+2]]:4 : 0 private func hidden() { } } S().visible()
apache-2.0
xwu/swift
test/Interop/Cxx/templates/explicit-class-specialization.swift
5
714
// RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-cxx-interop) // // REQUIRES: executable_test import ExplicitClassSpecialization import StdlibUnittest var TemplatesTestSuite = TestSuite("TemplatesTestSuite") TemplatesTestSuite.test("explicit-specialization") { let specializedInt = SpecializedIntWrapper(value: 7) var specializedMagicInt = WrapperWithSpecialization(t: specializedInt) expectEqual(specializedMagicInt.doubleIfSpecializedElseTriple(), 14) let nonSpecializedInt = NonSpecializedIntWrapper(value: 7) var nonSpecializedMagicInt = WrapperWithoutSpecialization(t: nonSpecializedInt) expectEqual(nonSpecializedMagicInt.doubleIfSpecializedElseTriple(), 21) } runAllTests()
apache-2.0
programersun/HiChongSwift
HiChongSwift/LCYNetworking.swift
1
13494
// // LCYNetworking.swift // HiChongSwift // // Created by eagle on 14/12/4. // Copyright (c) 2014年 Duostec. All rights reserved. // enum LCYApi: String { case TwitterAdd = "Twitter/twitter_add" case TwitterList = "Twitter/twitter_list" case TwitterKeeperInfo = "Twitter/keeper_info" case twitterPersonal = "Twitter/twitter_personal" case TwitterStar = "Twitter/twitter_star" case TwitterCommentList = "Twitter/twitter_comment_list" case TwitterCommentAdd = "Twitter/twitter_comment_add" case TwitterStarDel = "Twitter/twitter_star_del" case TwitterRemindInfo = "Twitter/twitter_remind_info" case TwitterDelete = "Twitter/twitter_del" case SquareGetSquareCategory = "Square/getSquareCategory" /// Deprecated case SquareHome = "Square/home" case SquaregetSquareList = "Square/getSquareList" case SquareMerchantInfo = "Square/merchant_info" case SquareCommentAdd = "Square/comment_add" case SquareCommentList = "Square/comment_list" case UserLogin = "User/login" case UserAuthcode = "User/register_authcode" case UserRegister = "User/register" case UserGetInfo = "User/getUserInfoByID" case UserModifySingle = "User/modifySingleProperty" case UserModifyLocation = "User/modifyLocation" case UserModifyInfo = "User/modifyInfo" case UserChangeLocation = "User/changeLocation" case UserAttention = "User/attention" case UserFansList = "User/fans_list" case UserFriendList = "User/friend_list" case UserSearchFriend = "User/search_friend" case UserSearchFriend2 = "User/search_friend2" case UserResetPasswordAuthcode = "User/reset_password_authcode" case UserSetPassword = "User/setPassword" case UserModifyBackgroundImage = "User/modifyBackgroundImage" case UserModifyImage = "User/modifyImage" case PetGetDetail = "Pet/GetPetDetailByID" case PetAllType = "PetStyle/searchAllTypePets" case PetSubType = "PetStyle/searchDetailByID" case PetAdd = "Pet/petAdd" case PetUpdatePetInfo = "Pet/updatePetInfo" case PetUploadPetImage = "Pet/UploadPetImage" case WikiToday = "Ency/getTodayEncy" case WikiIsCollect = "Ency/is_collect" case WikiCollect = "Ency/setCollect" case WikiCollectList = "Ency/getCollectArticle" case WikiMore = "Ency/searchEncy" case WikiGetAD = "/Ency/getAd" } enum LCYMimeType: String { case PNG = "image/png" case JPEG = "image/jpeg" } class LCYNetworking { private let hostURL = "http://123.57.7.88/admin/index.php/Api/" private let commonURL = "http://123.57.7.88/admin/index.php/Common/Upload/ios" private let ArticleHTMLComponent = "Ency/ency_article/ency_id/" private let WikiHtmlComponent = "Ency/category_article/cate_id/" /** 百度地图ak,由开发者 icylydia 提供 */ private let BaiduAK = "0G8SXbO2PwwGRLTzsIMj0dxi" /** 大众点评,由开发者 icylydia 提供 */ private let DianpingHost = "http://api.dianping.com/v1/business/find_businesses" private let DianpingAppKey = "0900420225" private let DianpingAppSecret = "c3385423913745e992079187dc08d33d" private enum RequestType { case GET case POST } class var sharedInstance: LCYNetworking { struct Singleton { static let instance = LCYNetworking() } return Singleton.instance } func Dianping(parameters: [String: String], success: ((object: NSDictionary) -> ())?, failure: ((error: NSError) -> ())?) { let manager = AFHTTPRequestOperationManager() manager.responseSerializer = AFJSONResponseSerializer() var mutpara = parameters mutpara.extend(["platform": "2"]) let keys = sorted(mutpara.keys) let signStringA = reduce(keys, DianpingAppKey) { (prefix, element) -> String in prefix + element + mutpara[element]! } let signStringB = signStringA + DianpingAppSecret let sign = signStringB.SHA_1() mutpara.extend(["appkey": DianpingAppKey, "sign": sign]) println("request 大众点评 with parameters: \(mutpara)") manager.GET(DianpingHost, parameters: mutpara, success: { (operation, object) -> Void in println("success in dianping ====> \(operation.responseString)") if let unwrappedSuccess = success { unwrappedSuccess(object: object as! NSDictionary) } }) { (operation, error) -> Void in println("error \(error)") println("\(operation.responseString)") if let unwrappedFailure = failure { unwrappedFailure(error: error) } } } func POSTAndGET(Api: LCYApi, GETParameters: [String: String]?, POSTParameters: NSDictionary!, success: ((object: NSDictionary) -> Void)?, failure: ((error: NSError!)->Void)?) { var URLString = Api.rawValue if let get = GETParameters { URLString += "?" URLString += reduce(get.keys, "", { $0 + $1 + "=" + get[$1]! + "&" }) requestWith(.POST, Api: URLString, parameters: POSTParameters, success: success, failure: failure) } else { if let unwrapped = failure { unwrapped(error: NSError()) } } } func POST(Api: LCYApi, parameters: NSDictionary!, success: ((object: NSDictionary) -> Void)?, failure: ((error: NSError!)->Void)?) { requestWith(.POST, Api: Api.rawValue, parameters: parameters, success: success, failure: failure) } func GET(Api: LCYApi, parameters: NSDictionary!, success: ((object: NSDictionary) -> Void)?, failure: ((error: NSError!)->Void)?) { requestWith(.GET, Api: Api.rawValue, parameters: parameters, success: success, failure: failure) } func POSTNONEJSON(Api: LCYApi, parameters: NSDictionary!, success: ((responseString: String) -> Void)?, failure: ((error: NSError!)->Void)?) { let manager = AFHTTPRequestOperationManager() manager.responseSerializer = AFHTTPResponseSerializer() manager.responseSerializer.acceptableContentTypes = NSSet(objects: "text/html", "text/plain") as Set<NSObject> let absoluteURL = hostURL + Api.rawValue manager.POST(absoluteURL, parameters: parameters, success: { (operation, object) -> Void in println("success in \"\(Api.rawValue)\" ====> \(operation.responseString)") if let unwrappedSuccess = success { unwrappedSuccess(responseString: operation.responseString) } }) { (operation, error) -> Void in println("error \(error)") println("\(operation.responseString)") if let unwrappedFailure = failure { unwrappedFailure(error: error) } } } private func requestWith(type: RequestType, Api: String, parameters: NSDictionary!, success: ((object: NSDictionary) -> Void)?, failure: ((error: NSError!)->Void)?) { let manager = AFHTTPRequestOperationManager() manager.responseSerializer = AFJSONResponseSerializer() manager.responseSerializer.acceptableContentTypes = NSSet(objects: "text/html", "text/plain") as Set<NSObject> let absoluteURL = hostURL + Api println("Request: \(absoluteURL)\nwith Parameters: \(parameters)") switch type { case .GET: manager.GET(absoluteURL, parameters: parameters, success: { (operation, object) -> Void in println("success in \"\(Api)\" ====> \(operation.responseString)") if let unwrappedSuccess = success { unwrappedSuccess(object: object as! NSDictionary) } }) { (operation, error) -> Void in println("error \(error)") if let unwrappedFailure = failure { unwrappedFailure(error: error) } } case .POST: manager.POST(absoluteURL, parameters: parameters, success: { (operation, object) -> Void in println("success in \"\(Api)\" ====> \(operation.responseString)") if let unwrappedSuccess = success { unwrappedSuccess(object: object as! NSDictionary) } }) { (operation, error) -> Void in println("error \(error)") println("\(operation.responseString)") if let unwrappedFailure = failure { unwrappedFailure(error: error) } } } } func POSTFile(Api: LCYApi, parameters: NSDictionary!, fileKey: String!, fileData: NSData!, fileName: String!, mimeType: LCYMimeType, success: ((object: NSDictionary) -> Void)?, failure: ((error: NSError) -> Void)?) { let manager = AFHTTPRequestOperationManager() manager.responseSerializer = AFJSONResponseSerializer() manager.responseSerializer.acceptableContentTypes = NSSet(objects: "text/html", "text/plain") as Set<NSObject> let absoluteURL = hostURL + Api.rawValue manager.POST(absoluteURL, parameters: parameters, constructingBodyWithBlock: { (formData: AFMultipartFormData!) -> Void in formData.appendPartWithFileData(fileData, name: fileKey, fileName: fileName, mimeType: mimeType.rawValue) return }, success: { (operation, object) -> Void in println("success in \"\(Api.rawValue)\" ====> \(operation.responseString)") if let unwrappedSuccess = success { unwrappedSuccess(object: object as! NSDictionary) } }) { (operation, error) -> Void in println("error \(error)") if let unwrappedFailure = failure { unwrappedFailure(error: error) } } } func POSTMultipleFile(Api: LCYApi, parameters: NSDictionary!, fileKey: String!, fileData: [NSData]!, success: ((object: NSDictionary) -> Void)?, failure: ((error: NSError) -> Void)?) { let manager = AFHTTPRequestOperationManager() manager.responseSerializer = AFJSONResponseSerializer() manager.responseSerializer.acceptableContentTypes = NSSet(objects: "text/html", "text/plain") as Set<NSObject> let absoluteURL = hostURL + Api.rawValue println("posting file, please wait!") manager.POST(absoluteURL, parameters: parameters, constructingBodyWithBlock: { (formData: AFMultipartFormData!) -> Void in for data in fileData { formData.appendPartWithFileData(data, name: fileKey, fileName: "\(data.hash).jpg", mimeType: LCYMimeType.JPEG.rawValue) } return }, success: { (operation, object) -> Void in println("success in \"\(Api.rawValue)\" ====> \(operation.responseString)") if let unwrappedSuccess = success { unwrappedSuccess(object: object as! NSDictionary) } }) { (operation, error) -> Void in println("error \(error)") if let unwrappedFailure = failure { unwrappedFailure(error: error) } } } func POSTCommonFile(fileKey: String!, fileData: NSData!, fileName: String!, mimeType: LCYMimeType, success: ((object: NSDictionary) -> Void)?, failure: ((error: NSError) -> Void)?) { let manager = AFHTTPRequestOperationManager() manager.responseSerializer = AFJSONResponseSerializer() manager.responseSerializer.acceptableContentTypes = NSSet(objects: "text/html", "text/plain") as Set<NSObject> let absoluteURL = commonURL manager.POST(absoluteURL, parameters: nil, constructingBodyWithBlock: { (formData: AFMultipartFormData!) -> Void in formData.appendPartWithFileData(fileData, name: fileKey, fileName: fileName, mimeType: mimeType.rawValue) return }, success: { (operation, object) -> Void in println("success in upload ====> \(operation.responseString)") if let unwrappedSuccess = success { unwrappedSuccess(object: object as! NSDictionary) } }) { (operation, error) -> Void in println("error \(error)") if let unwrappedFailure = failure { unwrappedFailure(error: error) } } } func WikiHTMLAddress(cateID: String) -> String { return "\(hostURL)\(ArticleHTMLComponent)\(cateID)" } func WikiDetailHTMLAddress(cateID: String) -> String { return "\(hostURL)\(WikiHtmlComponent)\(cateID)" } }
apache-2.0
iOSreverse/DWWB
DWWB/DWWB/Classes/Home(首页)/HomeModel/Status.swift
1
1278
// // Status.swift // DWWB // // Created by xmg on 16/4/9. // Copyright © 2016年 NewDee. All rights reserved. // import UIKit class Status: NSObject { // MARK: - 属性 var created_at : String? //微博创建时间 var source : String? //微博来源 var text : String? //微博的正文 var mid : Int = 0 //微博的ID var user : User? //微博对应的用户 var pic_urls : [[String : String]]? //微博的配图 var retweeted_status : Status? //微博对应的转发的微博 // MARK: - 自定义构造函数 init(dict : [String : AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) // 1.将用户字典转成用户模型对象 if let userDict = dict["user"] as? [String : AnyObject] { user = User(dict: userDict) } // 2将转发微博字典转成转发微博模型对象 if let retweetedStatusDict = dict["retweeted_status"] as? [String : AnyObject] { retweeted_status = Status(dict: retweetedStatusDict) } } override func setValue(value: AnyObject?, forUndefinedKey key: String) {} }
apache-2.0
ifabijanovic/swtor-holonet
ios/HoloNet/Module/Forum/UI/CollectionViewCell/ForumThreadCollectionViewCell.swift
1
1469
// // ForumThreadCollectionViewCell.swift // SWTOR HoloNet // // Created by Ivan Fabijanovic on 20/03/15. // Copyright (c) 2015 Ivan Fabijanović. All rights reserved. // import UIKit class ForumThreadCollectionViewCell: UICollectionViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var devImageView: UIImageView! @IBOutlet weak var stickyImageView: UIImageView! @IBOutlet weak var repliesViewsLabel: UILabel! @IBOutlet weak var accessoryView: UIImageView! override func apply(theme: Theme) { self.titleLabel.textColor = theme.contentTitle self.titleLabel.font = UIFont.systemFont(ofSize: theme.textSize.rawValue) self.authorLabel.textColor = theme.contentText self.authorLabel.font = UIFont.systemFont(ofSize: theme.textSize.rawValue - 2.0) self.repliesViewsLabel.textColor = theme.contentText self.repliesViewsLabel.font = UIFont.systemFont(ofSize: theme.textSize.rawValue - 2.0) if self.accessoryView.image == nil { self.accessoryView.image = UIImage(named: "Forward")?.withRenderingMode(.alwaysTemplate) } self.accessoryView.tintColor = theme.contentTitle let selectedBackgroundView = UIView() selectedBackgroundView.backgroundColor = theme.contentHighlightBackground self.selectedBackgroundView = selectedBackgroundView } }
gpl-3.0
LarsStegman/helios-for-reddit
Sources/Authorization/Token/UserToken.swift
1
3090
// // UserToken.swift // Helios // // Created by Lars Stegman on 13-01-17. // Copyright © 2017 Stegman. All rights reserved. // import Foundation struct UserToken: Token, Equatable { let username: String? let accessToken: String let refreshToken: String? let scopes: [Scope] let expiresAt: Date var authorizationType: Authorization { if let name = username { return .user(name: name) } else { return .application } } var refreshable: Bool { return refreshToken != nil } init(username: String?, accessToken: String, refreshToken: String?, scopes: [Scope], expiresAt: Date) { self.username = username self.accessToken = accessToken self.refreshToken = refreshToken self.scopes = scopes self.expiresAt = expiresAt } init(username: String?, token: UserToken) { self.init(username: username, accessToken: token.accessToken, refreshToken: token.refreshToken, scopes: token.scopes, expiresAt: token.expiresAt) } private enum CodingKeys: String, CodingKey { case username case accessToken = "access_token" case refreshToken = "refresh_token" case scopes = "scope" case expiresAt case expiresIn = "expires_in" } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if let name = username { try container.encode(name, forKey: .username) } else { try container.encodeNil(forKey: .username) } try container.encode(accessToken, forKey: .accessToken) try container.encode(refreshToken, forKey: .refreshToken) try container.encode(scopes, forKey: .scopes) try container.encode(expiresAt, forKey: .expiresAt) } init(from: Decoder) throws { let container = try from.container(keyedBy: CodingKeys.self) username = try container.decodeIfPresent(String.self, forKey: .username) accessToken = try container.decode(String.self, forKey: .accessToken) refreshToken = try container.decodeIfPresent(String.self, forKey: .refreshToken) if let scopesFromList = try? container.decode([Scope].self, forKey: .scopes) { scopes = scopesFromList } else { scopes = Scope.scopes(from: try container.decode(String.self, forKey: .scopes)) } if let expirationDate = try? container.decode(Date.self, forKey: .expiresAt) { expiresAt = expirationDate } else { expiresAt = Date(timeIntervalSinceNow: try container.decode(TimeInterval.self, forKey: .expiresIn)) } } static func ==(lhs: UserToken, rhs: UserToken) -> Bool { print("Equal!") return lhs.username == rhs.username && lhs.accessToken == rhs.accessToken && lhs.refreshToken == rhs.refreshToken && lhs.scopes == rhs.scopes && lhs.expiresAt == rhs.expiresAt } }
mit
dcunited001/SpectraNu
Spectra/Textures/TextureGenerator.swift
1
450
// // TextureGenerator.swift // // // Created by David Conner on 3/5/16. // // import Foundation import ModelIO import Swinject public protocol TextureGenerator { init(container: Container, args: [String: GeneratorArg]) func generate(container: Container, args: [String: GeneratorArg]) -> MDLTexture func processArgs(container: Container, args: [String: GeneratorArg]) func copy(container: Container) -> TextureGenerator }
mit
naokits/my-programming-marathon
TrySwift/TrySwiftExample/TrySwiftExample/MasterViewController.swift
1
3590
// // MasterViewController.swift // TrySwiftExample // // Created by Naoki Tsutsui on 9/1/16. // Copyright © 2016 Naoki Tsutsui. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [AnyObject]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(insertNewObject(_:))) self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { objects.insert(NSDate(), atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[indexPath.row] as! NSDate let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = objects[indexPath.row] as! NSDate cell.textLabel!.text = object.description return cell } 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 func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { objects.removeAtIndex(indexPath.row) 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. } } }
mit
a2/arex-7
ArexKit/Functions/ReactiveCocoaAdditions.swift
1
612
import ReactiveCocoa /// Handles an error by discarding it. /// /// - parameter error: The error to "handle". /// /// - returns: An empty signal producer. public func catchAll<T, E>(error: E) -> SignalProducer<T, NoError> { return .empty } /// A function that accepts a parameter of arbitrary type and replaces it with a second value of arbitrary type. /// /// - parameter value: An ignored value. /// - parameter replacement: A constant value to return. /// /// - returns: The replacement value. public func replace<T, U>(replacement: T) -> (U) -> T { return { _ in return replacement } }
mit
pooi/SubwayAlerter
SubwayAlerter/TabbarController.swift
1
374
import UIKit class TabbarController : UITabBarController { override func viewDidLoad() { UITabBar.appearance().barTintColor = UIColor(red: 20/255.0, green: 20/255.0, blue: 20/255.0, alpha: 1.0) UITabBar.appearance().tintColor = UIColor.whiteColor() self.hidesBottomBarWhenPushed = true } }
bsd-3-clause
zmarvin/EnjoyMusic
Pods/Macaw/Source/model/draw/LinearGradient.swift
1
804
import Foundation open class LinearGradient: Gradient { open let x1: Double open let y1: Double open let x2: Double open let y2: Double public init(x1: Double = 0, y1: Double = 0, x2: Double = 0, y2: Double = 0, userSpace: Bool = false, stops: [Stop] = []) { self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 super.init( userSpace: userSpace, stops: stops ) } public init(degree: Double = 0, from: Color, to: Color) { self.x1 = degree >= 135 && degree < 270 ? 1 : 0 self.y1 = degree < 225 ? 0 : 1 self.x2 = degree < 90 || degree >= 315 ? 1 : 0 self.y2 = degree >= 45 && degree < 180 ? 1 : 0 super.init( userSpace: false, stops: [Stop(offset: 0, color: from), Stop(offset: 1, color: to)] ) } }
mit
sayheyrickjames/codepath-dev
week2/week2-class1/furry-friends/furry-friends/ViewController.swift
1
513
// // ViewController.swift // furry-friends // // Created by Rick James! Chatas on 5/11/15. // Copyright (c) 2015 SayHey. All rights reserved. // import UIKit class ViewController: UIViewController { 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. } }
gpl-2.0
sayheyrickjames/codepath-dev
week3/week3-homework-mailbox-round2/week3-homework-mailbox/week3-homework-mailbox/AppDelegate.swift
2
2160
// // AppDelegate.swift // week3-homework-mailbox // // Created by Rick James! Chatas on 5/24/15. // Copyright (c) 2015 SayHey. All rights reserved. // import UIKit @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:. } }
gpl-2.0
louisdh/panelkit
PanelKitTests/StateTests.swift
1
3489
// // StateTests.swift // PanelKitTests // // Created by Louis D'hauwe on 16/11/2017. // Copyright © 2017 Silver Fox. All rights reserved. // import XCTest import UIKit @testable import PanelKit class StateTests: XCTestCase { var viewController: StateViewController! var navigationController: UINavigationController! override func setUp() { super.setUp() viewController = StateViewController() navigationController = UINavigationController(rootViewController: viewController) navigationController.view.frame = CGRect(origin: .zero, size: CGSize(width: 1024, height: 768)) let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = navigationController window.makeKeyAndVisible() XCTAssertNotNil(navigationController.view) XCTAssertNotNil(viewController.view) if UIDevice.current.userInterfaceIdiom == .phone { XCTFail("Test does not work on an iPhone") } } override func tearDown() { super.tearDown() // Put teardown code here. This method is called after the invocation of each test method in the class. } func testFloatPanel() { viewController.float(viewController.panel1VC, at: CGRect(x: 200, y: 200, width: 300, height: 300)) XCTAssert(viewController.panel1VC.isFloating) } func testPinMultiplePanelsRight() { viewController.pin(viewController.panel1VC, to: .right, atIndex: 0) viewController.pin(viewController.panel2VC, to: .right, atIndex: 0) XCTAssert(viewController.numberOfPanelsPinned(at: .right) == 2) XCTAssert(viewController.panel1VC.isPinned) XCTAssert(viewController.panel2VC.isPinned) } func testPinMultiplePanelsLeft() { viewController.pin(viewController.panel1VC, to: .left, atIndex: 0) viewController.pin(viewController.panel2VC, to: .left, atIndex: 0) XCTAssert(viewController.numberOfPanelsPinned(at: .left) == 2) XCTAssert(viewController.panel1VC.isPinned) XCTAssert(viewController.panel2VC.isPinned) } func testEncodeStates() { viewController.pin(viewController.panel1VC, to: .left, atIndex: 0) viewController.pin(viewController.panel2VC, to: .right, atIndex: 0) let states = viewController.panelStates guard let state1 = states[1] else { XCTFail("Expected state 1") return } guard let state2 = states[2] else { XCTFail("Expected state 2") return } XCTAssert(state1.pinnedMetadata?.side == .left) XCTAssert(state2.pinnedMetadata?.side == .right) } func testDecodeStates() { let json = """ { "2": { "floatingState": { "relativePosition": [0.4, 0.4], "zIndex": 0 } }, "1": { "pinnedMetadata": { "side": 0, "index": 0, "date": 532555376.97106999 } } } """ let decoder = JSONDecoder() let states = try! decoder.decode([Int: PanelState].self, from: json.data(using: .utf8)!) guard let state1 = states[1] else { XCTFail("Expected state 1") return } guard let state2 = states[2] else { XCTFail("Expected state 2") return } XCTAssert(state1.pinnedMetadata?.side == .left) XCTAssert(state2.floatingState?.zIndex == 0) viewController.restorePanelStates(states) XCTAssert(viewController.numberOfPanelsPinned(at: .left) == 1) XCTAssert(viewController.numberOfPanelsPinned(at: .right) == 0) XCTAssert(viewController.panel1VC.isPinned) XCTAssert(viewController.panel2VC.isFloating) } }
mit
syoung-smallwisdom/ResearchUXFactory-iOS
ResearchUXFactory/NSDictionary+Utilities.swift
1
2433
// // NSDictionary+Utilities.swift // ResearchUXFactory // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation extension NSDictionary { public func objectWithResourceDictionary() -> Any? { guard let resourceName = self["resourceName"] as? String else { return nil } let bundleName = self["resourceBundle"] as? String let bundle = (bundleName != nil) ? Bundle(identifier: bundleName!) : nil guard let json = SBAResourceFinder.shared.json(forResource: resourceName, bundle: bundle) else { return nil } guard let classType = self["classType"] as? String else { return json } return SBAClassTypeMap.shared.object(with: json, classType: classType) } }
bsd-3-clause
pr0gramm3r8hai/DGSegmentedControl
DGSegmentedControl/ViewController.swift
1
1792
// // ViewController.swift // DGSegmentedControl // // Created by dip on 2/17/16. // Copyright © 2016 apple. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var segmentedControl: DGSegmentedControl! @IBOutlet weak var displayGround: UIView! @IBOutlet weak var info: UILabel! override func viewDidLoad() { super.viewDidLoad() decorateSegmentedControl() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK:- Action @IBAction func segmentValueChanged(_ sender: AnyObject) { if sender.selectedIndex == 0{ self.displayGround.backgroundColor = UIColor.gray self.info.text = "First Segment selected" } else { self.displayGround.backgroundColor = UIColor(red: 0.761, green: 0.722, blue: 0.580, alpha: 1.00) self.info.text = "Second Segment selected" } } //MARK:- Segment control func decorateSegmentedControl(){ segmentedControl.items = ["First Segment","Second Segment"] segmentedControl.font = UIFont(name: "Avenir-Black", size: 12) segmentedControl.borderColor = UIColor(red: 0.988, green: 0.820, blue: 0.447, alpha: 1.00) segmentedControl.selectedIndex = 0 segmentedControl.borderSize = 2 segmentedControl.thumbColor = UIColor(red: 0.988, green: 0.820, blue: 0.447, alpha: 1.00) segmentedControl.selectedLabelColor = UIColor.black segmentedControl.thumUnderLineSize = 8 segmentedControl.font = UIFont.systemFont(ofSize: 18) self.segmentValueChanged(self.segmentedControl) } }
mit
icapps/ios_objective_c_workshop
Teacher/General Objective-C example/Pods/Faro/Sources/ServiceConvenienceExtension.swift
1
5980
import Foundation /// The perform methods are preferred but these methods are for convenience. /// They do some default error handling. /// These functions are deprecated!!! extension Service { // MARK: - Results transformed to Model(s) // MARK: - Update /// Performs the call to the server. Provide a model /// - parameter call: where can the server be found? /// - parameter fail: if we cannot initialize the model this call will fail and print the failure. /// - parameter ok: returns initialized model @available(*, deprecated: 1.1, obsoleted: 2.0, message: "You should use the `perform` functions in `Service` with result enum.") open func performUpdate<ModelType: Deserializable & Updatable>(_ call: Call, on updateModel: ModelType, autoStart: Bool = true, fail: @escaping (FaroError)->(), ok:@escaping (ModelType)->()) { perform(call, on: updateModel, autoStart: autoStart) { (result) in switch result { case .model(let model): guard let model = model else { let faroError = FaroError.malformed(info: "UpdateModel \(updateModel) could not be updated. Maybe you did not implement update correctly failed?") self.print(faroError, and: fail) return } ok(model) case .models( _ ): let faroError = FaroError.malformed(info: "Requested a single response be received a collection.") self.print(faroError, and: fail) default: self.handle(result, and: fail) } } } // MARK: - Create // MARK: - Single model response /// Performs the call to the server. Provide a model /// - parameter call: where can the server be found? /// - parameter fail: if we cannot initialize the model this call will fail and print the failure. /// - parameter ok: returns initialized model @available(*, deprecated: 1.1, obsoleted: 2.0, message: "You should use the `perform` functions in `Service` with result enum.") open func performSingle<ModelType: Deserializable>(_ call: Call, autoStart: Bool = true, fail: @escaping (FaroError)->(), ok:@escaping (ModelType)->()) { perform(call, autoStart: autoStart) { (result: Result<ModelType>) in switch result { case .model(let model): guard let model = model else { let faroError = FaroError.malformed(info: "Model could not be initialized. Maybe your init(from raw:) failed?") self.print(faroError, and: fail) return } ok(model) case .models( _ ): let faroError = FaroError.malformed(info: "Requested a single response be received a collection.") self.print(faroError, and: fail) default: self.handle(result, and: fail) } } } // MARK: - Collection model response /// Performs the call to the server. Provide a model /// - parameter call: where can the server be found? /// - parameter fail: if we cannot initialize the model this call will fail and print the failure. /// - parameter ok: returns initialized array of models @available(*, deprecated: 1.1, obsoleted: 2.0, message: "You should use the `perform` functions in `Service` with result enum.") open func performCollection<ModelType: Deserializable>(_ call: Call, autoStart: Bool = true, fail: @escaping (FaroError)->(), ok:@escaping ([ModelType])->()) { perform(call, autoStart: autoStart) { (result: Result<ModelType>) in switch result { case .models(let models): guard let models = models else { let faroError = FaroError.malformed(info: "Model could not be initialized. Maybe your init(from raw:) failed?") self.print(faroError, and: fail) return } ok(models) default: self.handle(result, and: fail) } } } // MARK: - With Paging information @available(*, deprecated: 1.1, obsoleted: 2.0, message: "You should use the `perform` functions in `Service` with result enum.") open func performSingle<ModelType: Deserializable, PagingType: Deserializable>(_ call: Call, autoStart: Bool = true, page: @escaping(PagingType?)->(), fail: @escaping (FaroError)->(), ok:@escaping (ModelType)->()) { perform(call, page: page, autoStart: autoStart) { (result: Result<ModelType>) in switch result { case .model(let model): guard let model = model else { let faroError = FaroError.malformed(info: "Model could not be initialized. Maybe your init(from raw:) failed?") self.print(faroError, and: fail) return } ok(model) default: self.handle(result, and: fail) } } } @available(*, deprecated: 1.1, obsoleted: 2.0, message: "You should use the `perform` functions in `Service` with result enum.") open func performCollection<ModelType: Deserializable, PagingType: Deserializable>(_ call: Call, page: @escaping(PagingType?)->(), fail: @escaping (FaroError)->(), ok:@escaping ([ModelType])->()) { perform(call, page: page) { (result: Result<ModelType>) in switch result { case .models(let models): guard let models = models else { let faroError = FaroError.malformed(info: "Models could not be initialized. Maybe your init(from raw:) failed?") self.print(faroError, and: fail) return } ok(models) default: self.handle(result, and: fail) } } } }
mit
realm/SwiftLint
Tests/SwiftLintFrameworkTests/ObjectLiteralRuleTests.swift
1
2865
@testable import SwiftLintFramework import XCTest class ObjectLiteralRuleTests: XCTestCase { // MARK: - Instance Properties private let imageLiteralTriggeringExamples = ["", ".init"].flatMap { (method: String) -> [Example] in ["UI", "NS"].flatMap { (prefix: String) -> [Example] in [ Example("let image = ↓\(prefix)Image\(method)(named: \"foo\")") ] } } private let colorLiteralTriggeringExamples = ["", ".init"].flatMap { (method: String) -> [Example] in ["UI", "NS"].flatMap { (prefix: String) -> [Example] in [ Example("let color = ↓\(prefix)Color\(method)(red: 0.3, green: 0.3, blue: 0.3, alpha: 1)"), Example("let color = ↓\(prefix)Color\(method)(red: 100 / 255.0, green: 50 / 255.0, blue: 0, alpha: 1)"), Example("let color = ↓\(prefix)Color\(method)(white: 0.5, alpha: 1)") ] } } private var allTriggeringExamples: [Example] { return imageLiteralTriggeringExamples + colorLiteralTriggeringExamples } // MARK: - Test Methods func testObjectLiteralWithImageLiteral() { // Verify ObjectLiteral rule for when image_literal is true. let baseDescription = ObjectLiteralRule.description let nonTriggeringColorLiteralExamples = colorLiteralTriggeringExamples.removingViolationMarkers() let nonTriggeringExamples = baseDescription.nonTriggeringExamples + nonTriggeringColorLiteralExamples let description = baseDescription.with(nonTriggeringExamples: nonTriggeringExamples) .with(triggeringExamples: imageLiteralTriggeringExamples) verifyRule(description, ruleConfiguration: ["image_literal": true, "color_literal": false]) } func testObjectLiteralWithColorLiteral() { // Verify ObjectLiteral rule for when color_literal is true. let baseDescription = ObjectLiteralRule.description let nonTriggeringImageLiteralExamples = imageLiteralTriggeringExamples.removingViolationMarkers() let nonTriggeringExamples = baseDescription.nonTriggeringExamples + nonTriggeringImageLiteralExamples let description = baseDescription.with(nonTriggeringExamples: nonTriggeringExamples) .with(triggeringExamples: colorLiteralTriggeringExamples) verifyRule(description, ruleConfiguration: ["image_literal": false, "color_literal": true]) } func testObjectLiteralWithImageAndColorLiteral() { // Verify ObjectLiteral rule for when image_literal & color_literal are true. let description = ObjectLiteralRule.description.with(triggeringExamples: allTriggeringExamples) verifyRule(description, ruleConfiguration: ["image_literal": true, "color_literal": true]) } }
mit
adolfogarza/SweetDate
SweetDate/Date+String.swift
1
677
// // Date+String.swift // Demo // // Created by Adolfo on 7/26/17. // Copyright © 2017 AdolfoGarza. All rights reserved. // import Foundation extension Date { public static func fromString(Date: String, Format: dateFormat) -> Date? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = Format.rawValue return dateFormatter.date(from: Date) } } extension String { public func dateWithFormat(Format: dateFormat) -> Date? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = Format.rawValue return dateFormatter.date(from: self) } }
mit
22377832/ccyswift
Extense/PhotoExtense/PhotoEditingViewController.swift
1
2792
// // PhotoEditingViewController.swift // PhotoExtense // // Created by sks on 17/1/25. // Copyright © 2017年 chen. All rights reserved. // import UIKit import Photos import PhotosUI class PhotoEditingViewController: UIViewController, PHContentEditingController { var input: PHContentEditingInput? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - PHContentEditingController func canHandle(_ adjustmentData: PHAdjustmentData) -> Bool { // Inspect the adjustmentData to determine whether your extension can work with past edits. // (Typically, you use its formatIdentifier and formatVersion properties to do this.) return false } func startContentEditing(with contentEditingInput: PHContentEditingInput, placeholderImage: UIImage) { // Present content for editing, and keep the contentEditingInput for use when closing the edit session. // If you returned true from canHandleAdjustmentData:, contentEditingInput has the original image and adjustment data. // If you returned false, the contentEditingInput has past edits "baked in". input = contentEditingInput } func finishContentEditing(completionHandler: @escaping ((PHContentEditingOutput?) -> Void)) { // Update UI to reflect that editing has finished and output is being rendered. // Render and provide output on a background queue. DispatchQueue.global().async { // Create editing output from the editing input. let output = PHContentEditingOutput(contentEditingInput: self.input!) // Provide new adjustments and render output to given location. // output.adjustmentData = <#new adjustment data#> // let renderedJPEGData = <#output JPEG#> // renderedJPEGData.writeToURL(output.renderedContentURL, atomically: true) // Call completion handler to commit edit to Photos. completionHandler(output) // Clean up temporary files, etc. } } var shouldShowCancelConfirmation: Bool { // Determines whether a confirmation to discard changes should be shown to the user on cancel. // (Typically, this should be "true" if there are any unsaved changes.) return false } func cancelContentEditing() { // Clean up temporary files, etc. // May be called after finishContentEditingWithCompletionHandler: while you prepare output. } }
mit
Stitch7/Instapod
Instapod/Player/Remote/ProgressSlider/PlayerRemoteProgressSlider.swift
1
4010
// // PlayerRemoteProgressSlider.swift // Instapod // // Created by Christopher Reitz on 07.03.16. // Copyright © 2016 Christopher Reitz. All rights reserved. // import UIKit import PKHUD @IBDesignable class PlayerRemoteProgressSlider: UISlider { // MARK: - Properties var isMoving = false var scrubbingSpeed = PlayerRemoteProgressSliderScrubbingSpeed.high var realPositionValue: Float = 0.0 var beganTrackingLocation = CGPoint(x: 0.0, y: 0.0) // MARK: - Touch tracking override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { let beginTracking = super.beginTracking(touch, with: event) if beginTracking { // Set the beginning tracking location to the centre of the current // position of the thumb. This ensures that the thumb is correctly re-positioned // when the touch position moves back to the track after tracking in one // of the slower tracking zones. let thumbRect = self.thumbRect(forBounds: bounds, trackRect: trackRect(forBounds: bounds), value: value) let x = thumbRect.origin.x + thumbRect.size.width / 2.0 let y = thumbRect.origin.y + thumbRect.size.height / 2.0 beganTrackingLocation = CGPoint(x: x, y: y) realPositionValue = value } return beginTracking } override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { guard isTracking else { return false } let previousLocation = touch.previousLocation(in: self) let currentLocation = touch.location(in: self) let trackingOffset = currentLocation.x - previousLocation.x // Find the scrubbing speed that curresponds to the touch's vertical offset let verticalOffset = fabs(currentLocation.y - beganTrackingLocation.y) if let lowerScrubbingSpeed = scrubbingSpeed.lowerScrubbingSpeed(forOffset: verticalOffset) { scrubbingSpeed = lowerScrubbingSpeed if scrubbingSpeed == .high { HUD.hide(animated: true) } else { HUD.allowsInteraction = true HUD.show(.label(scrubbingSpeed.stringValue)) } } let trackRect = self.trackRect(forBounds: bounds) realPositionValue = realPositionValue + (maximumValue - minimumValue) * Float(trackingOffset / trackRect.size.width) let valueAdjustment: Float = scrubbingSpeed.rawValue * (maximumValue - minimumValue) * Float(trackingOffset / trackRect.size.width) var thumbAdjustment: Float = 0.0 if ((beganTrackingLocation.y < currentLocation.y) && (currentLocation.y < previousLocation.y)) || ((beganTrackingLocation.y > currentLocation.y) && (currentLocation.y > previousLocation.y)) { thumbAdjustment = (realPositionValue - value) / Float(1 + fabs(currentLocation.y - beganTrackingLocation.y)) } value += valueAdjustment + thumbAdjustment if isContinuous { sendActions(for: .valueChanged) } return true } override func endTracking(_ touch: UITouch?, with event: UIEvent?) { guard isTracking else { return } scrubbingSpeed = .high sendActions(for: .touchUpInside) HUD.hide(animated: true) } // MARK: - Styling override func trackRect(forBounds bounds: CGRect) -> CGRect { var trackRect = super.trackRect(forBounds: bounds) trackRect.size.width = bounds.width trackRect.origin.x = 0 trackRect.origin.y = 0 trackRect.size.height = 4 return trackRect } override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect { var rect = super.thumbRect(forBounds: bounds, trackRect: rect, value: value) let x = rect.origin.x - 4 let y = rect.origin.y + 6 rect.origin = CGPoint(x: x, y: y) return rect } }
mit
lecason/UICountingLabel
UICountingLabel/AppDelegate.swift
1
2145
// // AppDelegate.swift // UICountingLabel // // Created by EyreFree on 15/4/14. // Copyright (c) 2015 EyreFree. All rights reserved. // import UIKit @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:. } }
gpl-2.0
finngaida/wwdc
2016/Pods/PeekPop/PeekPop/PeekPopManager.swift
1
4615
// // PeekPopManager.swift // PeekPop // // Created by Roy Marmelstein on 12/03/2016. // Copyright © 2016 Roy Marmelstein. All rights reserved. // import Foundation class PeekPopManager { let peekPop: PeekPop var viewController: UIViewController { get {return peekPop.viewController} } var targetViewController: UIViewController? var index: Int = 0 private var peekPopView: PeekPopView? private lazy var peekPopWindow: UIWindow = { let window = UIWindow(frame: UIScreen.mainScreen().bounds) window.windowLevel = UIWindowLevelAlert window.rootViewController = UIViewController() return window }() init(peekPop: PeekPop) { self.peekPop = peekPop } //MARK: PeekPop /// Prepare peek pop view if peek and pop gesture is possible func peekPopPossible(context: PreviewingContext, touchLocation: CGPoint, tag: Int) -> Bool { // Return early if no target view controller is provided by delegate method guard let targetVC = context.delegate.previewingContext(context, viewControllerForLocation: touchLocation, tag: tag) else { return false } // Create PeekPopView let view = PeekPopView() peekPopView = view // Take view controller screenshot if let viewControllerScreenshot = viewController.view.screenshotView() { peekPopView?.viewControllerScreenshot = viewControllerScreenshot peekPopView?.blurredScreenshots = self.generateBlurredScreenshots(viewControllerScreenshot) } // Take source view screenshot let rect = viewController.view.convertRect(context.sourceRect, fromView: context.sourceView) peekPopView?.sourceViewScreenshot = viewController.view.screenshotView(true, rect: rect) peekPopView?.sourceViewRect = rect // Take target view controller screenshot targetVC.view.frame = viewController.view.bounds peekPopView?.targetViewControllerScreenshot = targetVC.view.screenshotView(false) targetViewController = targetVC return true } func generateBlurredScreenshots(image: UIImage) -> [UIImage] { var images = [UIImage]() images.append(image) for i in 1...3 { let radius: CGFloat = CGFloat(Double(i) * 8.0 / 3.0) if let blurredScreenshot = blurImageWithRadius(image, radius: radius) { images.append(blurredScreenshot) } } return images } func blurImageWithRadius(image: UIImage, radius: CGFloat) -> UIImage? { return image.applyBlurWithRadius(CGFloat(radius), tintColor: nil, saturationDeltaFactor: 1.0, maskImage: nil) } /// Add window to heirarchy when peek pop begins func peekPopBegan() { peekPopWindow.alpha = 0.0 peekPopWindow.hidden = false peekPopWindow.makeKeyAndVisible() if let peekPopView = peekPopView { peekPopWindow.addSubview(peekPopView) } peekPopView?.frame = viewController.view.bounds peekPopView?.didAppear() UIView.animateWithDuration(0.2, animations: { () -> Void in self.peekPopWindow.alpha = 1.0 }) } /** Animated progress for context - parameter progress: A value between 0.0 and 1.0 - parameter context: PreviewingContext */ func animateProgressForContext(progress: CGFloat, context: PreviewingContext?) { (progress < 0.99) ? peekPopView?.animateProgress(progress) : commitTarget(context) } /** Commit target. - parameter context: PreviewingContext */ func commitTarget(context: PreviewingContext?){ guard let targetViewController = targetViewController, context = context else { return } context.delegate.previewingContext(context, commitViewController: targetViewController) peekPopEnded() } /** Peek pop ended - parameter animated: whether or not window removal should be animated */ func peekPopEnded() { UIView.animateWithDuration(0.2, animations: { () -> Void in self.peekPopWindow.alpha = 0.0 }) { (finished) -> Void in self.peekPop.peekPopGestureRecognizer?.resetValues() self.peekPopWindow.hidden = true self.peekPopView?.removeFromSuperview() self.peekPopView = nil } } }
gpl-2.0
fluidsonic/JetPack
Sources/Extensions/MapKit/MKMapRect.swift
1
2311
import MapKit public extension MKMapRect { init(region: MKCoordinateRegion) { let bottomLeft = MKMapPoint(CLLocationCoordinate2D(latitude: region.center.latitude + region.span.latitudeDelta / 2, longitude: region.center.longitude - region.span.longitudeDelta / 2)) let topRight = MKMapPoint(CLLocationCoordinate2D(latitude: region.center.latitude - region.span.latitudeDelta / 2, longitude: region.center.longitude + region.span.longitudeDelta / 2)) self = MKMapRect( x: min(bottomLeft.x, topRight.x), y: min(bottomLeft.y, topRight.y), width: abs(bottomLeft.x - topRight.x), height: abs(bottomLeft.y - topRight.y) ) } @available(*, unavailable, message: "use .insetBy(dx:dy)") mutating func insetBy(horizontally horizontal: Double, vertically vertical: Double = 0) { self = insetBy(dx: horizontal, dy: vertical) } @available(*, unavailable, message: "use .insetBy(dx:dy)") mutating func insetBy(vertically vertical: Double) { self = insetBy(dx: 0, dy: vertical) } @available(*, unavailable, renamed: "insetBy(dx:dy:)") func insettedBy(horizontally horizontal: Double, vertically vertical: Double = 0) -> MKMapRect { return insetBy(dx: horizontal, dy: vertical) } @available(*, unavailable, message: "use .insetBy(dx:dy)") func insettedBy(vertically vertical: Double) -> MKMapRect { return insetBy(dx: 0, dy: vertical) } mutating func scaleBy(_ scale: Double) { scaleBy(horizontally: scale, vertically: scale) } mutating func scaleBy(horizontally horizontal: Double, vertically vertical: Double = 1) { self = scaledBy(horizontally: horizontal, vertically: vertical) } mutating func scaleBy(vertically vertical: Double) { scaleBy(horizontally: 1, vertically: vertical) } func scaledBy(_ scale: Double) -> MKMapRect { return scaledBy(horizontally: scale, vertically: scale) } func scaledBy(horizontally horizontal: Double, vertically vertical: Double = 1) -> MKMapRect { return insetBy(dx: (size.width / 2) * horizontal, dy: (size.height / 2) * vertical) } func scaledBy(vertically vertical: Double) -> MKMapRect { return scaledBy(horizontally: 1, vertically: vertical) } } extension MKMapRect: Equatable { public static func == (a: MKMapRect, b: MKMapRect) -> Bool { return MKMapRectEqualToRect(a, b) } }
mit
zhuhaow/NEKit
test/Utils/IPRangeSpec.swift
2
3470
import Quick import Nimble @testable import NEKit class IPRangeSpec: QuickSpec { override func spec() { let cidrWrongSamples = [ ("127.0.0.132", IPRangeError.invalidCIDRFormat), ("13.1242.1241.1/3", IPRangeError.invalidCIDRFormat), ("123.122.33.21/35", IPRangeError.invalidMask), ("123.123.131.12/-1", IPRangeError.invalidCIDRFormat), ("123.123.131.12/", IPRangeError.invalidCIDRFormat) ] let cidrCorrectSamples = [ ("127.0.0.0/32", [IPAddress(fromString: "127.0.0.1")!]), ("127.0.0.0/31", [IPAddress(fromString: "127.0.0.1")!]), ("127.0.0.0/1", [IPAddress(fromString: "127.0.0.1")!]) ] let rangeWrongSamples = [ ("127.0.0.132", IPRangeError.invalidRangeFormat), ("13.1242.1241.1+3", IPRangeError.invalidRangeFormat), ("255.255.255.255+1", IPRangeError.invalidRange), ("0.0.0.1+4294967295", IPRangeError.invalidRange), ("123.123.131.12+", IPRangeError.invalidRangeFormat), ("12.124.51.23-1", IPRangeError.invalidRangeFormat) ] let rangeCorrectSamples = [ ("127.0.0.1+3", [IPAddress(fromString: "127.0.0.1")!]), ("255.255.255.255+0", [IPAddress(fromString: "255.255.255.255")!]), ("0.0.0.0+4294967295", [IPAddress(fromString: "0.0.0.0")!]) ] let ipSamples = [ ("127.0.0.1", [IPAddress(fromString: "127.0.0.1")!]) ] describe("IPRange initailization") { it("can be initailized with CIDR IP representation") { for sample in cidrWrongSamples { expect {try IPRange(withCIDRString: sample.0)}.to(throwError(sample.1)) } for sample in cidrCorrectSamples { expect {try IPRange(withCIDRString: sample.0)}.toNot(throwError()) } } it("can be initailized with IP range representation") { for sample in rangeWrongSamples { expect {try IPRange(withRangeString: sample.0)}.to(throwError(sample.1)) } for sample in rangeCorrectSamples { expect {try IPRange(withRangeString: sample.0)}.toNot(throwError()) } } it("can select the best way to initailize") { for sample in cidrCorrectSamples { expect {try IPRange(withString: sample.0)}.toNot(throwError()) } for sample in rangeCorrectSamples { expect {try IPRange(withString: sample.0)}.toNot(throwError()) } for sample in ipSamples { expect {try IPRange(withString: sample.0)}.toNot(throwError()) } } } describe("IPRange matching") { it ("Can match IPv4 address with mask") { let range = try! IPRange(withString: "8.8.8.8/24") expect(range.contains(ip: IPAddress(fromString: "8.8.8.0")!)).to(beTrue()) expect(range.contains(ip: IPAddress(fromString: "8.8.8.255")!)).to(beTrue()) expect(range.contains(ip: IPAddress(fromString: "8.8.7.255")!)).to(beFalse()) expect(range.contains(ip: IPAddress(fromString: "8.8.9.0")!)).to(beFalse()) } } } }
bsd-3-clause
ethanneff/organize
Organize/SettingViewController.swift
1
6794
import UIKit protocol SettingsDelegate: class { func settingsButtonPressed(button button: SettingViewController.Button) } class SettingViewController: UIViewController { // MARK: - properties weak var menu: SettingsDelegate? weak var delegate: SettingsDelegate? var buttons: [Int: Button] = [:] struct Button { let button: UIButton let detail: Detail } enum Detail: Int { case Notebook case NotebookTitle case NotebookChange case NotebookUncollapse case NotebookCollapse case NotebookHideReminder case NotebookDeleteCompleted case App case AppTutorial case AppColor case AppTimer case AppFeedback case AppShare case Cloud case CloudUpload case CloudDownload case Account case AccountAchievements case AccountEmail case AccountPassword case AccountDelete case AccountLogout case Upgrade case UpgradeBuy static var count: Int { return UpgradeBuy.hashValue+1 } var header: Bool { switch self { case .Notebook, .App, .Cloud, .Account, .Upgrade: return true default: return false } } var active: Bool { switch self { case .NotebookChange, .NotebookHideReminder, .AccountAchievements, .Upgrade, .UpgradeBuy, .Cloud, .CloudUpload, .CloudDownload: return false default: return true } } var highlighted: Bool { switch self { case .UpgradeBuy: return true default: return false } } var title: String { switch self { case .Notebook: return "Notebook" case .NotebookTitle: return "Change title" case .NotebookChange: return "Change notebook" case .NotebookCollapse: return "Collapse all" case .NotebookUncollapse: return "Expand all" case .NotebookHideReminder: return Constant.UserDefault.get(key: Constant.UserDefault.Key.IsRemindersHidden) as? Bool ?? false ? "Hide reminders" : "Show reminders" case .NotebookDeleteCompleted: return "Delete completed" case .App: return "App" case .AppTutorial: return "View tutorial" case .AppTimer: return Constant.UserDefault.get(key: Constant.UserDefault.Key.IsTimerActive) as? Bool ?? false ? "Modify timer" : "Activate timer" case .AppColor: return "Change color" case .AppFeedback: return "Send feedback" case .AppShare: return "Share with a friend" case .Cloud: return "Cloud" case .CloudUpload: return "Upload" case .CloudDownload: return "Download" case .Account: return "Account" case .AccountAchievements: return "View achievements" case .AccountEmail: return "Change email" case .AccountPassword: return "Change password" case .AccountDelete: return "Delete account" case .AccountLogout: return "Logout" case .Upgrade: return "Upgrade" case .UpgradeBuy: return "Buy the dev a coffee" } } } // MARK: - load override func loadView() { super.loadView() setupView() } private func setupView() { var constraints: [NSLayoutConstraint] = [] view.backgroundColor = Constant.Color.background // scroll view let scrollView = UIScrollView() var scrollViewContentSizeHeight: CGFloat = Constant.Button.padding scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) // buttons var prev: UIButton = UIButton() for i in 0..<Detail.count { if let detail = Detail(rawValue: i) { let button = UIButton() let enabled: Bool = detail.header ? false : true let color: UIColor = detail.header ? Constant.Color.border : Constant.Color.button let topItem: UIView = i == 0 ? scrollView : prev let topAttribute: NSLayoutAttribute = i == 0 ? .Top : .Bottom let topConstant: CGFloat = i == 0 ? Constant.Button.padding : detail.header ? Constant.Button.padding*2 : 0 button.tag = detail.rawValue button.hidden = !detail.active button.backgroundColor = Constant.Color.background button.layer.cornerRadius = 5 button.clipsToBounds = true button.setTitle(detail.title, forState: .Normal) button.setTitleColor(color, forState: .Normal) button.addTarget(self, action: #selector(buttonPressed(_:)), forControlEvents: .TouchUpInside) button.enabled = enabled button.contentHorizontalAlignment = detail.header ? .Center : .Left button.titleLabel?.font = .systemFontOfSize(Constant.Button.fontSize) button.translatesAutoresizingMaskIntoConstraints = false buttons[detail.rawValue] = Button(button: button, detail: detail) if !detail.active { continue } scrollView.addSubview(button) constraints.append(NSLayoutConstraint(item: button, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: Constant.Button.padding*2)) constraints.append(NSLayoutConstraint(item: button, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: -Constant.Button.padding*2)) constraints.append(NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: Constant.Button.height)) constraints.append(NSLayoutConstraint(item: button, attribute: .Top, relatedBy: .Equal, toItem: topItem, attribute: topAttribute, multiplier: 1, constant: topConstant)) scrollViewContentSizeHeight += topConstant + Constant.Button.height prev = button } } // scroll view constraints.append(NSLayoutConstraint(item: scrollView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: scrollView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: scrollView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: scrollView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0)) scrollView.contentSize = CGSize(width: 0, height: scrollViewContentSizeHeight) NSLayoutConstraint.activateConstraints(constraints) } // MARK: - button func buttonPressed(button: UIButton) { Util.animateButtonPress(button: button) if let button = buttons[button.tag] { delegate?.settingsButtonPressed(button: button) } } }
mit
PeterWang0124/PWSideViewControlSwift
Source/PWSideViewControlSwift.swift
1
12977
// // PWSideViewControlSwift.swift // PWSideViewControlSwift // // Created by PeterWang on 7/16/15. // Copyright (c) 2015 PeterWang. All rights reserved. // import UIKit // // MARK: - Public Enum // public enum PWSideViewCoverMode { case FullInSuperView case CoverNavigationBarView } public enum PWSideViewSizeMode { case Scale case Constant } public enum PWSideViewHorizontalDirection: Int { case Center case Left case Right } public enum PWSideViewVerticalDirection: Int { case Center case Top case Bottom } // // MARK: - PWSideViewDirection // public struct PWSideViewDirection { var horizontal: PWSideViewHorizontalDirection = .Left var vertical: PWSideViewVerticalDirection = .Center public init() {} public init(horizontal: PWSideViewHorizontalDirection, vertical: PWSideViewVerticalDirection) { self.horizontal = horizontal self.vertical = vertical } } // // MARK: - PWSideViewSize // public struct PWSideViewSize { var widthValue: CGFloat = 1 var widthSizeMode: PWSideViewSizeMode = .Scale var heightValue: CGFloat = 1 var heightSizeMode: PWSideViewSizeMode = .Scale public init() {} public init(widthValue: CGFloat, widthSizeMode: PWSideViewSizeMode, heightValue: CGFloat, heightSizeMode: PWSideViewSizeMode) { self.widthValue = widthValue self.widthSizeMode = widthSizeMode self.heightValue = heightValue self.heightSizeMode = heightSizeMode } } // // MARK: - PWSideViewAnimationItem // public struct PWSideViewAnimationItem { var path: UIBezierPath var duration: CFTimeInterval } // // MARK: - PWSideViewItem // public class PWSideViewItem: Equatable { private(set) var view: UIView! var hiddenPosition = PWSideViewDirection() var shownPosition = PWSideViewDirection() var size = PWSideViewSize() private var constraints = [NSLayoutConstraint]() private var canShowHideSideView: Bool = true private var hidden: Bool = true public init(embedView: UIView, hiddenPosition: PWSideViewDirection = PWSideViewDirection(), shownPosition: PWSideViewDirection = PWSideViewDirection(), size: PWSideViewSize = PWSideViewSize()) { self.view = embedView if hiddenPosition.horizontal == .Center && hiddenPosition.vertical == .Center { NSException(name: "Hidden position error", reason: "PWSideViewItem not support 'center' hidden, please set one of horizontal or vertical to be NOT 'center'.", userInfo: nil).raise() } if shownPosition.horizontal == .Center && shownPosition.vertical == .Center { NSException(name: "Shown position error", reason: "PWSideViewItem not support 'center' shown, please set one of horizontal or vertical to be NOT 'center'.", userInfo: nil).raise() } self.hiddenPosition = hiddenPosition self.shownPosition = shownPosition self.size = size } } public func ==(lhs: PWSideViewItem, rhs: PWSideViewItem) -> Bool { return lhs.view == rhs.view } // // MARK: - PWSideViewControlSwift // public class PWSideViewControlSwift: UIView, UIGestureRecognizerDelegate { // MARK: - Public Variables var coverMode: PWSideViewCoverMode = .FullInSuperView { didSet { addToView() } } var maskColor: UIColor = UIColor(white: 0, alpha: 0.5) { didSet { configView() } } var maskViewDidTapped: (() -> Void)? // MARK: - Private Variables private var embeddedView: UIView! private var sideViewItems = [PWSideViewItem]() // MARK: - Initializer public init(embeddedView: UIView) { super.init(frame: embeddedView.frame) self.embeddedView = embeddedView setupView() } public override init(frame: CGRect) { super.init(frame: frame) self.embeddedView = defaultEmbeddedView() setupView() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.embeddedView = defaultEmbeddedView() setupView() } private func defaultEmbeddedView() -> UIView { if let currendtWindow = UIApplication.sharedApplication().keyWindow { return currendtWindow } else { let defaultEmbeddedView = UIView(frame: UIScreen.mainScreen().bounds) return defaultEmbeddedView } } // MARK: - Public functioins public func addSideViewItem(item: PWSideViewItem) -> Int { let index = self.sideViewItems.count self.sideViewItems.append(item) addSubview(item.view) setupSideViewLayoutConstraintsByItem(item, hidden: true) return index } public func isSideViewItemHiddenAtIndex(itemIndex: Int) -> Bool { if 0..<self.sideViewItems.count ~= itemIndex { return self.sideViewItems[itemIndex].hidden } return true } public func sideViewItemAtIndex(itemIndex: Int, hidden: Bool, withDuration duration: NSTimeInterval, animated: Bool, completed: (() -> Void)?) { guard 0..<self.sideViewItems.count ~= itemIndex else { return } let item = self.sideViewItems[itemIndex] guard item.canShowHideSideView else { return } item.canShowHideSideView = false item.hidden = hidden removeConstraints(item.constraints) item.view.removeConstraints(item.constraints) setupSideViewLayoutConstraintsByItem(item, hidden: hidden) if animated { if !hidden { self.hidden = false } UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseOut, animations: { _ in self.alpha = hidden ? 0 : 1 self.layoutIfNeeded() }, completion: { _ in item.canShowHideSideView = true self.hidden = hidden completed?() }) } else { self.alpha = hidden ? 0 : 1 item.canShowHideSideView = true self.hidden = hidden layoutIfNeeded() completed?() } } public func hideAllSideViewItemWithDuration(duration: NSTimeInterval, animated: Bool, completed: (() -> Void)?) { var needHideSideViewItems = [PWSideViewItem]() for item in self.sideViewItems { if !item.hidden { needHideSideViewItems.append(item) } } for item in needHideSideViewItems { item.canShowHideSideView = false item.hidden = true removeConstraints(item.constraints) item.view.removeConstraints(item.constraints) setupSideViewLayoutConstraintsByItem(item, hidden: true) } if animated { UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseOut, animations: { _ in self.alpha = 0 self.layoutIfNeeded() }, completion: { _ in for item in needHideSideViewItems { item.canShowHideSideView = true } self.hidden = true completed?() }) } else { self.alpha = 0 for item in needHideSideViewItems { item.canShowHideSideView = true } self.hidden = true layoutIfNeeded() completed?() } } // MARK: - Private functions private func setupView() { self.hidden = true self.alpha = 0 let tapGR = UITapGestureRecognizer(target: self, action: #selector(PWSideViewControlSwift.maskViewTapped(_:))) tapGR.delegate = self addGestureRecognizer(tapGR) configView() // Add view to addToView() } private func addToView() { switch self.coverMode { case .CoverNavigationBarView: if let currendtWindow = UIApplication.sharedApplication().delegate?.window ?? nil { currendtWindow.addSubview(self) setupViewLayoutConstraints() } default: self.embeddedView.addSubview(self) setupViewLayoutConstraints() } } private func setupViewLayoutConstraints() { if let superView = self.superview { self.translatesAutoresizingMaskIntoConstraints = false let topConstraint = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: superView, attribute: .Top, multiplier: 1, constant: 0) superView.addConstraint(topConstraint) let bottomConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: superView, attribute: .Bottom, multiplier: 1, constant: 0) superView.addConstraint(bottomConstraint) let leadingConstraint = NSLayoutConstraint(item: self, attribute: .Leading, relatedBy: .Equal, toItem: superView, attribute: .Leading, multiplier: 1, constant: 0) superView.addConstraint(leadingConstraint) let trailingConstraint = NSLayoutConstraint(item: self, attribute: .Trailing, relatedBy: .Equal, toItem: superView, attribute: .Trailing, multiplier: 1, constant: 0) superView.addConstraint(trailingConstraint) } } private func setupSideViewLayoutConstraintsByItem(sideViewItem: PWSideViewItem, hidden: Bool) { sideViewItem.view.translatesAutoresizingMaskIntoConstraints = false let pos: PWSideViewDirection if hidden { pos = sideViewItem.hiddenPosition } else { pos = sideViewItem.shownPosition } // Horizontal. switch pos.horizontal { case .Center: let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) case .Left: let attribute: NSLayoutAttribute = hidden ? .Trailing : .Leading let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: attribute, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) case .Right: let attribute: NSLayoutAttribute = hidden ? .Leading : .Trailing let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: attribute, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) } // Vertical. switch pos.vertical { case .Center: let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) case .Top: let attribute: NSLayoutAttribute = hidden ? .Bottom : .Top let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: attribute, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) case .Bottom: let attribute: NSLayoutAttribute = hidden ? .Top : .Bottom let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: attribute, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) } // Width. switch sideViewItem.size.widthSizeMode { case .Scale: let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: sideViewItem.size.widthValue, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) case .Constant: let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: sideViewItem.size.widthValue) sideViewItem.view.addConstraint(constraint) sideViewItem.constraints.append(constraint) } switch sideViewItem.size.heightSizeMode { case .Scale: let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: sideViewItem.size.heightValue, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) case .Constant: let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: sideViewItem.size.heightValue) sideViewItem.view.addConstraint(constraint) sideViewItem.constraints.append(constraint) } } // MARK: - Configure private func configView() { self.backgroundColor = self.maskColor setNeedsDisplay() } // MARK: - Gesture Recognizer Action func maskViewTapped(recognizer: UITapGestureRecognizer) { if self.maskViewDidTapped != nil { self.maskViewDidTapped!() } else { } } public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { if let touchView = touch.view where (touchView.isDescendantOfView(self) && touchView != self) { return false } return true } }
mit
danielloureda/congenial-sniffle
Project13/Project13/AppDelegate.swift
1
2177
// // AppDelegate.swift // Project13 // // Created by Daniel Loureda Arteaga on 14/6/17. // Copyright © 2017 Dano. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
ScoutHarris/WordPress-iOS
WordPressKit/WordPressKitTests/WordPressComRestApiTests.swift
1
12315
import Foundation import XCTest import OHHTTPStubs import WordPressShared @testable import WordPressKit class WordPressComRestApiTests: XCTestCase { let wordPressComRestApi = "https://public-api.wordpress.com/rest/" let wordPressMediaRoute = "v1.1/sites/0/media/" let wordPressMediaNewEndpoint = "v1.1/sites/0/media/new" override func setUp() { super.setUp() } override func tearDown() { super.tearDown() OHHTTPStubs.removeAllStubs() } fileprivate func isRestAPIRequest() -> OHHTTPStubsTestBlock { return { request in let pathWithLocale = WordPressComRestApi.pathByAppendingPreferredLanguageLocale(self.wordPressMediaRoute) return request.url?.absoluteString == self.wordPressComRestApi + pathWithLocale } } fileprivate func isRestAPIMediaNewRequest() -> OHHTTPStubsTestBlock { return { request in let pathWithLocale = WordPressComRestApi.pathByAppendingPreferredLanguageLocale(self.wordPressMediaNewEndpoint) return request.url?.absoluteString == self.wordPressComRestApi + pathWithLocale } } func testSuccessfullCall() { stub(condition: isRestAPIRequest()) { request in let stubPath = OHPathForFile("WordPressComRestApiMedia.json", type(of: self)) return fixture(filePath: stubPath!, headers: ["Content-Type" as NSObject: "application/json" as AnyObject]) } let expect = self.expectation(description: "One callback should be invoked") let api = WordPressComRestApi(oAuthToken: "fakeToken") api.GET(wordPressMediaRoute, parameters: nil, success: { (responseObject: AnyObject, httpResponse: HTTPURLResponse?) in expect.fulfill() XCTAssert(responseObject is [String: AnyObject], "The response should be a dictionary") }, failure: { (error, httpResponse) in expect.fulfill() XCTFail("This call should be successfull") } ) self.waitForExpectations(timeout: 2, handler: nil) } func testInvalidTokenFailedCall() { stub(condition: isRestAPIRequest()) { request in let stubPath = OHPathForFile("WordPressComRestApiFailRequestInvalidToken.json", type(of: self)) return fixture(filePath: stubPath!, status: 400, headers: ["Content-Type" as NSObject: "application/json" as AnyObject]) } let expect = self.expectation(description: "One callback should be invoked") let api = WordPressComRestApi(oAuthToken: "fakeToken") api.GET(wordPressMediaRoute, parameters: nil, success: { (responseObject: AnyObject, httpResponse: HTTPURLResponse?) in expect.fulfill() XCTFail("This call should fail") }, failure: { (error, httpResponse) in expect.fulfill() XCTAssert(error.domain == String(reflecting: WordPressComRestApiError.self), "The error should a WordPressComRestApiError") XCTAssert(error.code == Int(WordPressComRestApiError.invalidToken.rawValue), "The error code should be invalid token") }) self.waitForExpectations(timeout: 2, handler: nil) } func testInvalidJSONReceivedFailedCall() { stub(condition: isRestAPIRequest()) { request in let stubPath = OHPathForFile("WordPressComRestApiFailInvalidJSON.json", type(of: self)) return fixture(filePath: stubPath!, status: 200, headers: ["Content-Type" as NSObject: "application/json" as AnyObject]) } let expect = self.expectation(description: "One callback should be invoked") let api = WordPressComRestApi(oAuthToken: "fakeToken") api.GET(wordPressMediaRoute, parameters: nil, success: { (responseObject: AnyObject, httpResponse: HTTPURLResponse?) in expect.fulfill() XCTFail("This call should fail") }, failure: { (error, httpResponse) in expect.fulfill() XCTAssert(error.domain == "NSCocoaErrorDomain", "The error domain should be NSCocoaErrorDomain") XCTAssert(error.code == Int(3840), "The code should be invalid token") }) self.waitForExpectations(timeout: 2, handler: nil) } func testInvalidJSONSentFailedCall() { stub(condition: isRestAPIMediaNewRequest()) { request in let stubPath = OHPathForFile("WordPressComRestApiFailInvalidInput.json", type(of: self)) return fixture(filePath: stubPath!, status: 400, headers: ["Content-Type" as NSObject: "application/json" as AnyObject]) } let expect = self.expectation(description: "One callback should be invoked") let api = WordPressComRestApi(oAuthToken: "fakeToken") api.POST(wordPressMediaNewEndpoint, parameters: nil, success: { (responseObject: AnyObject, httpResponse: HTTPURLResponse?) in expect.fulfill() XCTFail("This call should fail") }, failure: { (error, httpResponse) in expect.fulfill() XCTAssert(error.domain == String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError") XCTAssert(error.code == Int(WordPressComRestApiError.invalidInput.rawValue), "The error code should be invalid input") }) self.waitForExpectations(timeout: 2, handler: nil) } func testUnauthorizedFailedCall() { stub(condition: isRestAPIMediaNewRequest()) { request in let stubPath = OHPathForFile("WordPressComRestApiFailUnauthorized.json", type(of: self)) return fixture(filePath: stubPath!, status: 403, headers: ["Content-Type" as NSObject: "application/json" as AnyObject]) } let expect = self.expectation(description: "One callback should be invoked") let api = WordPressComRestApi(oAuthToken: "fakeToken") api.POST(wordPressMediaNewEndpoint, parameters: nil, success: { (responseObject: AnyObject, httpResponse: HTTPURLResponse?) in expect.fulfill() XCTFail("This call should fail") }, failure: { (error, httpResponse) in expect.fulfill() XCTAssert(error.domain == String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError") XCTAssert(error.code == Int(WordPressComRestApiError.authorizationRequired.rawValue), "The error code should be AuthorizationRequired") }) self.waitForExpectations(timeout: 2, handler: nil) } func testMultipleErrorsFailedCall() { stub(condition: isRestAPIMediaNewRequest()) { request in let stubPath = OHPathForFile("WordPressComRestApiMultipleErrors.json", type(of: self)) return fixture(filePath: stubPath!, status: 403, headers: ["Content-Type" as NSObject: "application/json" as AnyObject]) } let expect = self.expectation(description: "One callback should be invoked") let api = WordPressComRestApi(oAuthToken: "fakeToken") api.POST(wordPressMediaNewEndpoint, parameters: nil, success: { (responseObject: AnyObject, httpResponse: HTTPURLResponse?) in expect.fulfill() XCTFail("This call should fail") }, failure: { (error, httpResponse) in expect.fulfill() XCTAssert(error.domain == String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError") XCTAssert(error.code == Int(WordPressComRestApiError.uploadFailed.rawValue), "The error code should be AuthorizationRequired") }) self.waitForExpectations(timeout: 2, handler: nil) } func testThatAppendingLocaleWorks() { let path = "path/path" let localeKey = "locale" let preferredLanguageIdentifier = WordPressComLanguageDatabase().deviceLanguage.slug let expectedPath = "\(path)?\(localeKey)=\(preferredLanguageIdentifier)" let localeAppendedPath = WordPressComRestApi.pathByAppendingPreferredLanguageLocale(path) XCTAssert(localeAppendedPath == expectedPath, "Expected the locale to be appended to the path as (\(expectedPath)) but instead encountered (\(localeAppendedPath)).") } func testThatAppendingLocaleWorksWithExistingParams() { let path = "path/path?someKey=value" let localeKey = "locale" let preferredLanguageIdentifier = WordPressComLanguageDatabase().deviceLanguage.slug let expectedPath = "\(path)&\(localeKey)=\(preferredLanguageIdentifier)" let localeAppendedPath = WordPressComRestApi.pathByAppendingPreferredLanguageLocale(path) XCTAssert(localeAppendedPath == expectedPath, "Expected the locale to be appended to the path as (\(expectedPath)) but instead encountered (\(localeAppendedPath)).") } func testThatAppendingLocaleIgnoresIfAlreadyIncluded() { let localeKey = "locale" let preferredLanguageIdentifier = WordPressComLanguageDatabase().deviceLanguage.slug let path = "path/path?\(localeKey)=\(preferredLanguageIdentifier)&someKey=value" let localeAppendedPath = WordPressComRestApi.pathByAppendingPreferredLanguageLocale(path) XCTAssert(localeAppendedPath == path, "Expected the locale to already be appended to the path as (\(path)) but instead encountered (\(localeAppendedPath)).") } func testStreamMethodCallWithInvalidFile() { stub(condition: isRestAPIMediaNewRequest()) { request in let stubPath = OHPathForFile("WordPressComRestApiMedia.json", type(of: self)) return fixture(filePath: stubPath!, headers: ["Content-Type" as NSObject: "application/json" as AnyObject]) } let expect = self.expectation(description: "One callback should be invoked") let api = WordPressComRestApi(oAuthToken: "fakeToken") let filePart = FilePart(parameterName: "file", url: URL(fileURLWithPath: "/a.txt") as URL, filename: "a.txt", mimeType: "image/jpeg") api.multipartPOST(wordPressMediaNewEndpoint, parameters: nil, fileParts: [filePart], success: { (responseObject: AnyObject, httpResponse: HTTPURLResponse?) in expect.fulfill() XCTFail("This call should fail") }, failure: { (error, httpResponse) in expect.fulfill() } ) self.waitForExpectations(timeout: 2, handler: nil) } func testStreamMethodParallelCalls() { stub(condition: isRestAPIMediaNewRequest()) { request in let stubPath = OHPathForFile("WordPressComRestApiMedia.json", type(of: self)) return fixture(filePath: stubPath!, headers: ["Content-Type" as NSObject: "application/json" as AnyObject]) } guard let mediaPath = OHPathForFile("test-image.jpg", type(of: self)) else { return } let mediaURL = URL(fileURLWithPath: mediaPath) let expect = self.expectation(description: "One callback should be invoked") let api = WordPressComRestApi(oAuthToken: "fakeToken") let filePart = FilePart(parameterName: "media[]", url: mediaURL as URL, filename: "test-image.jpg", mimeType: "image/jpeg") let progress1 = api.multipartPOST(wordPressMediaNewEndpoint, parameters: nil, fileParts: [filePart], success: { (responseObject: AnyObject, httpResponse: HTTPURLResponse?) in XCTFail("This call should fail") }, failure: { (error, httpResponse) in print(error) XCTAssert(error.domain == NSURLErrorDomain, "The error domain should be NSURLErrorDomain") XCTAssert(error.code == NSURLErrorCancelled, "The error code should be NSURLErrorCancelled") } ) progress1?.cancel() api.multipartPOST(wordPressMediaNewEndpoint, parameters: nil, fileParts: [filePart], success: { (responseObject: AnyObject, httpResponse: HTTPURLResponse?) in expect.fulfill() }, failure: { (error, httpResponse) in expect.fulfill() XCTFail("This call should succesful") } ) self.waitForExpectations(timeout: 5, handler: nil) } }
gpl-2.0
Johennes/firefox-ios
Client/Frontend/Browser/OpenWithSettingsViewController.swift
1
4793
/* 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 import Shared class OpenWithSettingsViewController: UITableViewController { typealias MailtoProviderEntry = (name: String, scheme: String, enabled: Bool) var mailProviderSource = [MailtoProviderEntry]() private let prefs: Prefs private var currentChoice: String = "mailto" private let BasicCheckmarkCell = "BasicCheckmarkCell" init(prefs: Prefs) { self.prefs = prefs super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = Strings.SettingsOpenWithSectionName tableView.accessibilityIdentifier = "OpenWithPage.Setting.Options" tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: BasicCheckmarkCell) tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor let headerFooterFrame = CGRect(origin: CGPointZero, size: CGSize(width: self.view.frame.width, height: UIConstants.TableViewHeaderFooterHeight)) let headerView = SettingsTableSectionHeaderFooterView(frame: headerFooterFrame) headerView.titleLabel.text = Strings.SettingsOpenWithPageTitle headerView.showTopBorder = false headerView.showBottomBorder = true let footerView = SettingsTableSectionHeaderFooterView(frame: headerFooterFrame) footerView.showTopBorder = true footerView.showBottomBorder = false tableView.tableHeaderView = headerView tableView.tableFooterView = footerView NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(OpenWithSettingsViewController.appDidBecomeActive), name: UIApplicationDidBecomeActiveNotification, object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) appDidBecomeActive() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.prefs.setString(currentChoice, forKey: PrefsKeys.KeyMailToOption) } func appDidBecomeActive() { reloadMailProviderSource() updateCurrentChoice() tableView.reloadData() } func updateCurrentChoice() { var previousChoiceAvailable: Bool = false if let prefMailtoScheme = self.prefs.stringForKey(PrefsKeys.KeyMailToOption) { mailProviderSource.forEach({ (name, scheme, enabled) in if scheme == prefMailtoScheme { previousChoiceAvailable = enabled } }) } if !previousChoiceAvailable { self.prefs.setString(mailProviderSource[0].scheme, forKey: PrefsKeys.KeyMailToOption) } if let updatedMailToClient = self.prefs.stringForKey(PrefsKeys.KeyMailToOption) { self.currentChoice = updatedMailToClient } } func reloadMailProviderSource() { if let path = NSBundle.mainBundle().pathForResource("MailSchemes", ofType: "plist"), let dictRoot = NSArray(contentsOfFile: path) { mailProviderSource = dictRoot.map { dict in (name: dict["name"] as! String, scheme: dict["scheme"] as! String, enabled: canOpenMailScheme(dict["scheme"] as! String)) } } } func canOpenMailScheme(scheme: String) -> Bool { if let url = NSURL(string: scheme) { return UIApplication.sharedApplication().canOpenURL(url) } return false } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(BasicCheckmarkCell, forIndexPath: indexPath) let option = mailProviderSource[indexPath.row] cell.textLabel?.attributedText = NSAttributedString.tableRowTitle(option.name) cell.accessoryType = (currentChoice == option.scheme && option.enabled) ? .Checkmark : .None cell.textLabel?.textColor = option.enabled ? UIConstants.TableViewRowTextColor : UIConstants.TableViewDisabledRowTextColor cell.userInteractionEnabled = option.enabled return cell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mailProviderSource.count } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.currentChoice = mailProviderSource[indexPath.row].scheme tableView.reloadData() } }
mpl-2.0
andyyhope/Elbbbird
Elbbbird/Controller/ShotViewController.swift
1
2816
// // ShotViewController.swift // Elbbbird // // Created by Andyy Hope on 20/03/2016. // Copyright © 2016 Andyy Hope. All rights reserved. // import UIKit class ShotViewController: UIViewController { @IBOutlet var shotImageView: UIImageView! @IBOutlet var visualEffectContainerView: UIView! @IBOutlet var visualEffectView: UIVisualEffectView! @IBOutlet var tableView: UITableView! @IBOutlet var activityIndicatorView: UIActivityIndicatorView! var viewModel: ShotViewModel? { didSet { if tableView != nil { tableView.reloadData() activityIndicatorView.stopAnimating() } } } override func viewDidLoad() { super.viewDidLoad() tableView.register(ShotCommentTableViewCell) requestShot() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension ShotViewController : UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel?.comments.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: ShotCommentTableViewCell = tableView.dequeueReusableCell(forIndexPath: indexPath) guard let viewModel = viewModel?.viewModelForCommentCell(atIndexPath: indexPath) else { return cell } cell.usernameLabel.text = viewModel.username cell.commentLabel.text = viewModel.body // cell.likesLabel.text = viewModel.likes return cell } } extension ShotViewController : UITableViewDelegate { func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return ShotCommentTableViewCell.defaultHeight } } // MARK: - Request extension ShotViewController { func requestShot() { guard let shotID = viewModel?.shot.id else { return } DribbbleRequester.requestShot(forShotID: shotID) { [weak self] (shot) -> Void in guard let shot = shot else { return } self?.viewModel = ShotViewModel(shot: shot) self?.requestComments() } } func requestComments() { guard let shotID = viewModel?.shot.id else { return } DribbbleRequester.requestComments(forShotID: shotID) { [weak self] (comments) -> Void in guard let shot = self?.viewModel?.shot else { return } self?.viewModel = ShotViewModel(shot: shot, comments: comments) } } }
gpl-3.0
Tyrant2013/LeetCodePractice
LeetCodePractice/Easy/58_Length_Of_Last_Word.swift
1
1343
// // Length_Of_Last_Word.swift // LeetCodePractice // // Created by 庄晓伟 on 2018/2/11. // Copyright © 2018年 Zhuang Xiaowei. All rights reserved. // import UIKit //Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. // //If the last word does not exist, return 0. // //Note: A word is defined as a character sequence consists of non-space characters only. // //Example: // //Input: "Hello World" //Output: 5 class Length_Of_Last_Word: Solution { override func ExampleTest() { [ "Hello World", // 5 "a", // 1 "b ", // 1 ].forEach { str in print("str: \(str), last word len: \(self.lengthOfLastWord(str))") } } func lengthOfLastWord(_ s: String) -> Int { if s.count == 0 { return 0 } var len = s.count - 1 let sequeue = s.map({ $0 }) var ret = 0 while len >= 0 { if sequeue[len] != " " { ret += 1 } else { if ret == 0 && sequeue[len] == " " { len -= 1 continue } return ret } len -= 1 } return ret } }
mit
vinted/vinted-ab-ios
Carthage/Checkouts/CryptoSwift/Tests/Tests/Poly1305Tests.swift
1
3819
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // @testable import CryptoSwift import Foundation import XCTest final class Poly1305Tests: XCTestCase { func testPoly1305() { let key: Array<UInt8> = [0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc] let msg: Array<UInt8> = [0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1] let expectedMac: Array<UInt8> = [0xdd, 0xb9, 0xda, 0x7d, 0xdd, 0x5e, 0x52, 0x79, 0x27, 0x30, 0xed, 0x5c, 0xda, 0x5f, 0x90, 0xa4] XCTAssertEqual(try Poly1305(key: key).authenticate(msg), expectedMac) // extensions let msgData = Data( msg) XCTAssertEqual(try msgData.authenticate(with: Poly1305(key: key)), Data( expectedMac), "Invalid authentication result") } // https://github.com/krzyzanowskim/CryptoSwift/issues/183 func testIssue183() { let key: Array<UInt8> = [111, 53, 197, 181, 1, 92, 67, 199, 37, 92, 76, 167, 12, 35, 75, 226, 198, 34, 107, 84, 79, 6, 231, 10, 25, 221, 14, 155, 81, 244, 15, 203] let message: Array<UInt8> = [208, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 162, 210, 40, 78, 3, 161, 87, 187, 96, 253, 104, 187, 87, 87, 249, 56, 5, 156, 122, 121, 196, 192, 254, 58, 98, 22, 47, 151, 205, 201, 108, 143, 197, 99, 182, 109, 59, 63, 172, 111, 120, 185, 175, 129, 59, 126, 68, 140, 237, 126, 175, 49, 224, 249, 245, 37, 75, 252, 69, 215, 171, 27, 163, 16, 185, 239, 184, 144, 37, 131, 242, 12, 90, 134, 24, 237, 209, 127, 71, 86, 122, 173, 238, 73, 186, 58, 102, 112, 90, 217, 243, 251, 110, 85, 106, 18, 172, 167, 179, 173, 73, 125, 9, 129, 132, 80, 70, 4, 254, 178, 211, 200, 207, 231, 232, 17, 176, 127, 153, 120, 71, 164, 139, 56, 106, 71, 96, 79, 11, 213, 243, 66, 53, 167, 108, 233, 250, 136, 69, 190, 191, 12, 136, 24, 157, 202, 49, 158, 152, 150, 34, 88, 132, 112, 74, 168, 153, 116, 31, 7, 61, 60, 22, 199, 108, 187, 209, 114, 234, 185, 247, 41, 68, 184, 95, 169, 60, 126, 73, 59, 54, 126, 162, 90, 18, 32, 230, 123, 2, 40, 74, 177, 127, 219, 93, 186, 22, 75, 251, 101, 95, 160, 68, 235, 77, 2, 10, 202, 2, 0, 0, 0, 0, 0, 0, 0, 208, 0, 0, 0, 0, 0, 0, 0] let expectedMac: Array<UInt8> = [68, 216, 92, 163, 164, 144, 55, 43, 185, 18, 83, 92, 41, 133, 72, 168] XCTAssertEqual(try message.authenticate(with: Poly1305(key: key)), expectedMac) } static let allTests = [ ("testPoly1305", testPoly1305), ("testIssue183", testIssue183), ] }
mit
chinesemanbobo/PPDemo
Pods/Down/Source/AST/Nodes/ThematicBreak.swift
3
320
// // ThematicBreak.swift // Down // // Created by John Nguyen on 09.04.19. // import Foundation import libcmark public class ThematicBreak: BaseNode {} // MARK: - Debug extension ThematicBreak: CustomDebugStringConvertible { public var debugDescription: String { return "Thematic Break" } }
mit
legendecas/Rocket.Chat.iOS
Rocket.Chat.Shared/Extensions/UIColor+Hex.swift
1
11021
// // Color+HexAndCSSColorNames.swift // // Created by Norman Basham on 12/8/15. // Copyright © 2015 Black Labs. All rights reserved. // // 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 // swiftlint:disable force_unwrapping control_statement syntactic_sugar extension UIColor { /** Creates an immuatble UIColor instance specified by a hex string, CSS color name, or nil. - parameter hexString: A case insensitive String? representing a hex or CSS value e.g. - **"abc"** - **"abc7"** - **"#abc7"** - **"00FFFF"** - **"#00FFFF"** - **"00FFFF77"** - **"Orange", "Azure", "Tomato"** Modern browsers support 140 color names (<http://www.w3schools.com/cssref/css_colornames.asp>) - **"Clear"** [UIColor clearColor] - **"Transparent"** [UIColor clearColor] - **nil** [UIColor clearColor] - **empty string** [UIColor clearColor] */ convenience init(hex: String?) { let normalizedHexString: String = UIColor.normalize(hex) var c: CUnsignedInt = 0 Scanner(string: normalizedHexString).scanHexInt32(&c) self.init(red:UIColorMasks.redValue(c), green:UIColorMasks.greenValue(c), blue:UIColorMasks.blueValue(c), alpha:UIColorMasks.alphaValue(c)) } /** Returns a hex equivalent of this UIColor. - Parameter includeAlpha: Optional parameter to include the alpha hex. color.hexDescription() -> "ff0000" color.hexDescription(true) -> "ff0000aa" - Returns: A new string with `String` with the color's hexidecimal value. */ func hexDescription(_ includeAlpha: Bool = false) -> String { if self.cgColor.numberOfComponents == 4 { let components = self.cgColor.components let red = Float((components?[0])!) * 255.0 let green = Float((components?[1])!) * 255.0 let blue = Float((components?[2])!) * 255.0 let alpha = Float((components?[3])!) * 255.0 if (includeAlpha) { return String.init(format: "%02x%02x%02x%02x", Int(red), Int(green), Int(blue), Int(alpha)) } else { return String.init(format: "%02x%02x%02x", Int(red), Int(green), Int(blue)) } } else { return "Color not RGB." } } fileprivate enum UIColorMasks: CUnsignedInt { case redMask = 0xff000000 case greenMask = 0x00ff0000 case blueMask = 0x0000ff00 case alphaMask = 0x000000ff static func redValue(_ value: CUnsignedInt) -> CGFloat { let i: CUnsignedInt = (value & redMask.rawValue) >> 24 let f: CGFloat = CGFloat(i)/255.0 return f } static func greenValue(_ value: CUnsignedInt) -> CGFloat { let i: CUnsignedInt = (value & greenMask.rawValue) >> 16 let f: CGFloat = CGFloat(i)/255.0 return f } static func blueValue(_ value: CUnsignedInt) -> CGFloat { let i: CUnsignedInt = (value & blueMask.rawValue) >> 8 let f: CGFloat = CGFloat(i)/255.0 return f } static func alphaValue(_ value: CUnsignedInt) -> CGFloat { let i: CUnsignedInt = value & alphaMask.rawValue let f: CGFloat = CGFloat(i)/255.0 return f } } fileprivate static func normalize(_ hex: String?) -> String { guard var hexString = hex else { return "00000000" } let cssColor = cssToHexDictionairy[hexString.uppercased()] if cssColor != nil { return cssColor! + "ff" } let hasHash: Bool = hexString.hasPrefix("#") if (hasHash) { hexString = String(hexString.characters.dropFirst()) } if hexString.characters.count == 3 || hexString.characters.count == 4 { let redHex = hexString.substring(to: hexString.characters.index(hexString.startIndex, offsetBy: 1)) let greenHex = hexString.substring(with: Range<String.Index>(hexString.characters.index(hexString.startIndex, offsetBy: 1) ..< hexString.characters.index(hexString.startIndex, offsetBy: 2))) let blueHex = hexString.substring(with: Range<String.Index>(hexString.characters.index(hexString.startIndex, offsetBy: 2) ..< hexString.characters.index(hexString.startIndex, offsetBy: 3))) var alphaHex = "" if hexString.characters.count == 4 { alphaHex = hexString.substring(from: hexString.characters.index(hexString.startIndex, offsetBy: 3)) } hexString = redHex + redHex + greenHex + greenHex + blueHex + blueHex + alphaHex + alphaHex } let hasAlpha = hexString.characters.count > 7 if (!hasAlpha) { hexString += "ff" } return hexString } /** All modern browsers support the following 140 color names (see http://www.w3schools.com/cssref/css_colornames.asp) */ fileprivate static func hexFromCssName(_ cssName: String) -> String { let key = cssName.uppercased() let hex = cssToHexDictionairy[key] if hex == nil { return cssName } return hex! } fileprivate static let cssToHexDictionairy: Dictionary<String, String> = [ "CLEAR": "00000000", "TRANSPARENT": "00000000", "": "00000000", "ALICEBLUE": "F0F8FF", "ANTIQUEWHITE": "FAEBD7", "AQUA": "00FFFF", "AQUAMARINE": "7FFFD4", "AZURE": "F0FFFF", "BEIGE": "F5F5DC", "BISQUE": "FFE4C4", "BLACK": "000000", "BLANCHEDALMOND": "FFEBCD", "BLUE": "0000FF", "BLUEVIOLET": "8A2BE2", "BROWN": "A52A2A", "BURLYWOOD": "DEB887", "CADETBLUE": "5F9EA0", "CHARTREUSE": "7FFF00", "CHOCOLATE": "D2691E", "CORAL": "FF7F50", "CORNFLOWERBLUE": "6495ED", "CORNSILK": "FFF8DC", "CRIMSON": "DC143C", "CYAN": "00FFFF", "DARKBLUE": "00008B", "DARKCYAN": "008B8B", "DARKGOLDENROD": "B8860B", "DARKGRAY": "A9A9A9", "DARKGREY": "A9A9A9", "DARKGREEN": "006400", "DARKKHAKI": "BDB76B", "DARKMAGENTA": "8B008B", "DARKOLIVEGREEN": "556B2F", "DARKORANGE": "FF8C00", "DARKORCHID": "9932CC", "DARKRED": "8B0000", "DARKSALMON": "E9967A", "DARKSEAGREEN": "8FBC8F", "DARKSLATEBLUE": "483D8B", "DARKSLATEGRAY": "2F4F4F", "DARKSLATEGREY": "2F4F4F", "DARKTURQUOISE": "00CED1", "DARKVIOLET": "9400D3", "DEEPPINK": "FF1493", "DEEPSKYBLUE": "00BFFF", "DIMGRAY": "696969", "DIMGREY": "696969", "DODGERBLUE": "1E90FF", "FIREBRICK": "B22222", "FLORALWHITE": "FFFAF0", "FORESTGREEN": "228B22", "FUCHSIA": "FF00FF", "GAINSBORO": "DCDCDC", "GHOSTWHITE": "F8F8FF", "GOLD": "FFD700", "GOLDENROD": "DAA520", "GRAY": "808080", "GREY": "808080", "GREEN": "008000", "GREENYELLOW": "ADFF2F", "HONEYDEW": "F0FFF0", "HOTPINK": "FF69B4", "INDIANRED": "CD5C5C", "INDIGO": "4B0082", "IVORY": "FFFFF0", "KHAKI": "F0E68C", "LAVENDER": "E6E6FA", "LAVENDERBLUSH": "FFF0F5", "LAWNGREEN": "7CFC00", "LEMONCHIFFON": "FFFACD", "LIGHTBLUE": "ADD8E6", "LIGHTCORAL": "F08080", "LIGHTCYAN": "E0FFFF", "LIGHTGOLDENRODYELLOW": "FAFAD2", "LIGHTGRAY": "D3D3D3", "LIGHTGREY": "D3D3D3", "LIGHTGREEN": "90EE90", "LIGHTPINK": "FFB6C1", "LIGHTSALMON": "FFA07A", "LIGHTSEAGREEN": "20B2AA", "LIGHTSKYBLUE": "87CEFA", "LIGHTSLATEGRAY": "778899", "LIGHTSLATEGREY": "778899", "LIGHTSTEELBLUE": "B0C4DE", "LIGHTYELLOW": "FFFFE0", "LIME": "00FF00", "LIMEGREEN": "32CD32", "LINEN": "FAF0E6", "MAGENTA": "FF00FF", "MAROON": "800000", "MEDIUMAQUAMARINE": "66CDAA", "MEDIUMBLUE": "0000CD", "MEDIUMORCHID": "BA55D3", "MEDIUMPURPLE": "9370DB", "MEDIUMSEAGREEN": "3CB371", "MEDIUMSLATEBLUE": "7B68EE", "MEDIUMSPRINGGREEN": "00FA9A", "MEDIUMTURQUOISE": "48D1CC", "MEDIUMVIOLETRED": "C71585", "MIDNIGHTBLUE": "191970", "MINTCREAM": "F5FFFA", "MISTYROSE": "FFE4E1", "MOCCASIN": "FFE4B5", "NAVAJOWHITE": "FFDEAD", "NAVY": "000080", "OLDLACE": "FDF5E6", "OLIVE": "808000", "OLIVEDRAB": "6B8E23", "ORANGE": "FFA500", "ORANGERED": "FF4500", "ORCHID": "DA70D6", "PALEGOLDENROD": "EEE8AA", "PALEGREEN": "98FB98", "PALETURQUOISE": "AFEEEE", "PALEVIOLETRED": "DB7093", "PAPAYAWHIP": "FFEFD5", "PEACHPUFF": "FFDAB9", "PERU": "CD853F", "PINK": "FFC0CB", "PLUM": "DDA0DD", "POWDERBLUE": "B0E0E6", "PURPLE": "800080", "RED": "FF0000", "ROSYBROWN": "BC8F8F", "ROYALBLUE": "4169E1", "SADDLEBROWN": "8B4513", "SALMON": "FA8072", "SANDYBROWN": "F4A460", "SEAGREEN": "2E8B57", "SEASHELL": "FFF5EE", "SIENNA": "A0522D", "SILVER": "C0C0C0", "SKYBLUE": "87CEEB", "SLATEBLUE": "6A5ACD", "SLATEGRAY": "708090", "SLATEGREY": "708090", "SNOW": "FFFAFA", "SPRINGGREEN": "00FF7F", "STEELBLUE": "4682B4", "TAN": "D2B48C", "TEAL": "008080", "THISTLE": "D8BFD8", "TOMATO": "FF6347", "TURQUOISE": "40E0D0", "VIOLET": "EE82EE", "WHEAT": "F5DEB3", "WHITE": "FFFFFF", "WHITESMOKE": "F5F5F5", "YELLOW": "FFFF00", "YELLOWGREEN": "9ACD32" ] }
mit
jensmeder/DarkLightning
Examples/Messenger/iOS/Sources/AppDelegate.swift
1
1079
// // AppDelegate.swift // Messenger-iOS // // Created by Jens Meder on 05.04.17. // // import UIKit import DarkLightning @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var port: DarkLightning.Port? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let textView = Memory<UITextView?>(initialValue: nil) let navigationItem = Memory<UINavigationItem?>(initialValue: nil) port = DevicePort(delegate: MessengerDelegate(textView: textView, navigationItem: navigationItem)) port?.open() window = UIWindow() window?.rootViewController = UINavigationController( rootViewController: ViewController( title: "Disconnected", textView: textView, header: navigationItem, port: port! ) ) window?.makeKeyAndVisible() application.isIdleTimerDisabled = true return true } }
mit
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/GraphQLModel/BubbleQuizGraphQLModel.swift
1
2109
// // BubbleQuizGraphQLModel.swift // AwesomeCore // // Created by Leonardo Vinicius Kaminski Ferreira on 25/02/19. // import Foundation public struct BubbleQuizGraphQLModel { fileprivate static let cardModel = "id subtitle title description position type media{id title author { id name } type channel { id title }} settings { start_date theme_color icon } content_asset {id duration contentType filesize url renditions(labels: [\"mp4\", \"hls\"]) {id url status} captions {id is_default label language url} } small_cover_asset { url } large_cover_asset { url }" fileprivate static let quizCategoriesModelSrt: String = "{ ftuQuiz(id: 1) { id title subtitle questions{ id icon name title subtitle answers{ id title } } } }" static func quizCategoriesModel() -> [String: AnyObject] { return ["query": BubbleQuizGraphQLModel.quizCategoriesModelSrt as AnyObject] } // MARK: - Update bubble answers mutation fileprivate static var cardLimitText: String = ", cardLimit: 3" fileprivate static let mutateSubmitAnswers = "mutation { submitQuizResponse(distinctId: \"%@\", answers: [%@]%@){ startedAt, cards{ \(cardModel) }, currentCard{ \(cardModel) } } }" public static func submitAnswers(_ distinctId: String, answerIds: [Int], cardLimit: Bool = false) -> [String: AnyObject] { var ids: String = "" for id in answerIds { ids.append(contentsOf: ",\(id)") } let limit: String = cardLimit ? cardLimitText : "" return ["query": String(format: mutateSubmitAnswers, arguments: [distinctId, ids, limit]) as AnyObject] } // MARK: - User Journey Model private static let journeyModel = "{ journey(identifier: \"%@\"%@){ startedAt, cards{ \(cardModel) }, currentCard{ \(cardModel) } } }" public static func queryUserJourney(withIdentifier id: String, cardLimit: Bool = false) -> [String: AnyObject] { let limit: String = cardLimit ? cardLimitText : "" return ["query": String(format: journeyModel, arguments: [id, limit]) as AnyObject] } }
mit
nzaghini/mastering-reuse-viper
Weather/SharedContainer.swift
2
781
import Foundation import Swinject extension Container { // Shared container // We are still looking at the best way to achieve this with Swinject static let sharedContainer: Container = { let c = Container() c.register(WeatherService.self) { _ in ApixuWeatherService()} c.register(LocationService.self) { _ in ApixuLocationService()} c.register(LocationStoreService.self) { _ in RealmLocationStoreService()} c.register(WeatherListBuilder.self) { _ in WeatherListSwiftInjectBuilder()} c.register(WeatherDetailBuilder.self) { _ in WeatherDetailSwiftInjectBuilder()} c.register(WeatherLocationBuilder.self) { _ in WeatherLocationSwiftInjectBuilder()} return c }() }
mit
frajaona/LiFXSwiftKit
Pods/socks/Sources/SocksCore/Select.swift
1
3820
// Copyright (c) 2016, Kyle Fuller // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #if os(Linux) import Glibc @_exported import struct Glibc.timeval private let system_select = Glibc.select #else import Darwin @_exported import struct Darwin.timeval private let system_select = Darwin.select #endif extension timeval { public init(seconds: Int) { self = timeval(tv_sec: seconds, tv_usec: 0) } public init(seconds: Double) { let sec = Int(seconds) #if os(Linux) let intType = Int.self #else let intType = Int32.self #endif let microsec = intType.init((seconds - Double(sec)) * pow(10.0, 6)) self = timeval(tv_sec: sec, tv_usec: microsec) } } private func filter(_ sockets: [Descriptor]?, _ set: inout fd_set) -> [Descriptor] { return sockets?.filter { fdIsSet($0, &set) } ?? [] } public func select(reads: [Descriptor] = [], writes: [Descriptor] = [], errors: [Descriptor] = [], timeout: timeval? = nil) throws -> (reads: [Descriptor], writes: [Descriptor], errors: [Descriptor]) { var readFDs = fd_set() fdZero(&readFDs) reads.forEach { fdSet($0, &readFDs) } var writeFDs = fd_set() fdZero(&writeFDs) writes.forEach { fdSet($0, &writeFDs) } var errorFDs = fd_set() fdZero(&errorFDs) errors.forEach { fdSet($0, &errorFDs) } let maxFD = (reads + writes + errors).reduce(0, max) let result: Int32 if let timeout = timeout { var timeout = timeout result = system_select(maxFD + 1, &readFDs, &writeFDs, &errorFDs, &timeout) } else { result = system_select(maxFD + 1, &readFDs, &writeFDs, &errorFDs, nil) } if result == 0 { return ([], [], []) } else if result > 0 { return ( filter(reads, &readFDs), filter(writes, &writeFDs), filter(errors, &errorFDs) ) } throw SocksError(.selectFailed(reads: reads, writes: writes, errors: errors)) } extension RawSocket { /// Allows user to wait for the socket to have readable bytes for /// up to the specified timeout. Nil timeout means wait forever. /// Returns true if data is ready to be read, false if timed out. public func waitForReadableData(timeout: timeval?) throws -> Bool { let (readables, _, _) = try select(reads: [descriptor], timeout: timeout) return !readables.isEmpty } }
apache-2.0
wikimedia/apps-ios-wikipedia
Wikipedia/Code/WMFTableOfContentsAnimator.swift
1
14677
import UIKit import CocoaLumberjackSwift // MARK: - Delegate @objc public protocol WMFTableOfContentsAnimatorDelegate { func tableOfContentsAnimatorDidTapBackground(_ controller: WMFTableOfContentsAnimator) } open class WMFTableOfContentsAnimator: UIPercentDrivenInteractiveTransition, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning, UIGestureRecognizerDelegate, WMFTableOfContentsPresentationControllerTapDelegate, Themeable { fileprivate var theme = Theme.standard public func apply(theme: Theme) { self.theme = theme self.presentationController?.apply(theme: theme) } var displaySide = WMFTableOfContentsDisplaySide.left var displayMode = WMFTableOfContentsDisplayMode.modal // MARK: - init public required init(presentingViewController: UIViewController, presentedViewController: UIViewController) { self.presentingViewController = presentingViewController self.presentedViewController = presentedViewController self.isPresenting = true self.isInteractive = false presentationGesture = UIPanGestureRecognizer() super.init() presentationGesture.addTarget(self, action: #selector(WMFTableOfContentsAnimator.handlePresentationGesture(_:))) presentationGesture.maximumNumberOfTouches = 1 presentationGesture.delegate = self self.presentingViewController!.view.addGestureRecognizer(presentationGesture) } deinit { removeDismissalGestureRecognizer() presentationGesture.removeTarget(self, action: #selector(WMFTableOfContentsAnimator.handlePresentationGesture(_:))) presentationGesture.view?.removeGestureRecognizer(presentationGesture) } weak var presentingViewController: UIViewController? weak var presentedViewController: UIViewController? open var gesturePercentage: CGFloat = 0.4 weak open var delegate: WMFTableOfContentsAnimatorDelegate? fileprivate(set) open var isPresenting: Bool fileprivate(set) open var isInteractive: Bool // MARK: - WMFTableOfContentsPresentationControllerTapDelegate open func tableOfContentsPresentationControllerDidTapBackground(_ controller: WMFTableOfContentsPresentationController) { delegate?.tableOfContentsAnimatorDidTapBackground(self) } // MARK: - UIViewControllerTransitioningDelegate weak var presentationController: WMFTableOfContentsPresentationController? open func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { guard presented == self.presentedViewController else { return nil } let presentationController = WMFTableOfContentsPresentationController(presentedViewController: presented, presentingViewController: self.presentingViewController, tapDelegate: self) presentationController.apply(theme: theme) presentationController.displayMode = displayMode presentationController.displaySide = displaySide self.presentationController = presentationController return presentationController } open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { guard presented == self.presentedViewController else { return nil } self.isPresenting = true return self } open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { guard dismissed == self.presentedViewController else { return nil } self.isPresenting = false return self } open func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { if self.isInteractive { return self }else{ return nil } } open func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { if self.isInteractive { return self }else{ return nil } } // MARK: - UIViewControllerAnimatedTransitioning open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return self.isPresenting ? 0.5 : 0.8 } open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if isPresenting { removeDismissalGestureRecognizer() addDismissalGestureRecognizer(transitionContext.containerView) animatePresentationWithTransitionContext(transitionContext) } else { animateDismissalWithTransitionContext(transitionContext) } } var tocMultiplier:CGFloat { switch displaySide { case .left: return -1.0 case .right: return 1.0 case .center: fallthrough default: return UIApplication.shared.wmf_isRTL ? -1.0 : 1.0 } } // MARK: - Animation func animatePresentationWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) { let presentedController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)! let presentedControllerView = transitionContext.view(forKey: UITransitionContextViewKey.to)! let containerView = transitionContext.containerView // Position the presented view off the top of the container view var f = transitionContext.finalFrame(for: presentedController) f.origin.x += f.size.width * tocMultiplier presentedControllerView.frame = f containerView.addSubview(presentedControllerView) animateTransition(self.isInteractive, duration: self.transitionDuration(using: transitionContext), animations: { () -> Void in var f = presentedControllerView.frame f.origin.x -= f.size.width * self.tocMultiplier presentedControllerView.frame = f }, completion: {(completed: Bool) -> Void in let cancelled = transitionContext.transitionWasCancelled transitionContext.completeTransition(!cancelled) }) } func animateDismissalWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) { let presentedControllerView = transitionContext.view(forKey: UITransitionContextViewKey.from)! animateTransition(self.isInteractive, duration: self.transitionDuration(using: transitionContext), animations: { () -> Void in var f = presentedControllerView.frame switch self.displaySide { case .left: f.origin.x = -1*f.size.width break case .right: fallthrough case .center: fallthrough default: f.origin.x = transitionContext.containerView.bounds.size.width } presentedControllerView.frame = f }, completion: {(completed: Bool) -> Void in let cancelled = transitionContext.transitionWasCancelled transitionContext.completeTransition(!cancelled) }) } func animateTransition(_ interactive: Bool, duration: TimeInterval, animations: @escaping () -> Void, completion: ((Bool) -> Void)?){ if(interactive){ UIView.animate(withDuration: duration, delay: 0.0, options: UIView.AnimationOptions(), animations: { () -> Void in animations() }, completion: { (completed: Bool) -> Void in completion?(completed) }) }else{ UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .allowUserInteraction, animations: { animations() }, completion: {(completed: Bool) -> Void in completion?(completed) }) } } // MARK: - Gestures private let presentationGesture: UIPanGestureRecognizer var dismissalGesture: UIPanGestureRecognizer? func addDismissalGestureRecognizer(_ containerView: UIView) { let gesture = UIPanGestureRecognizer(target: self, action: #selector(WMFTableOfContentsAnimator.handleDismissalGesture(_:))) gesture.delegate = self containerView.addGestureRecognizer(gesture) dismissalGesture = gesture } func removeDismissalGestureRecognizer() { if let dismissalGesture = dismissalGesture { dismissalGesture.view?.removeGestureRecognizer(dismissalGesture) dismissalGesture.removeTarget(self, action: #selector(WMFTableOfContentsAnimator.handleDismissalGesture(_:))) } dismissalGesture = nil } @objc func handlePresentationGesture(_ gesture: UIScreenEdgePanGestureRecognizer) { switch(gesture.state) { case (.began): self.isInteractive = true self.presentingViewController?.present(self.presentedViewController!, animated: true, completion: nil) case (.changed): let translation = gesture.translation(in: gesture.view) let transitionProgress = max(min(translation.x * -tocMultiplier / self.presentedViewController!.view.bounds.maxX, 0.99), 0.01) self.update(transitionProgress) case (.ended): self.isInteractive = false let velocityRequiredToPresent = -gesture.view!.bounds.width * tocMultiplier let velocityRequiredToDismiss = -velocityRequiredToPresent let velocityX = gesture.velocity(in: gesture.view).x if velocityX*velocityRequiredToDismiss > 1 && abs(velocityX) > abs(velocityRequiredToDismiss){ cancel() return } if velocityX*velocityRequiredToPresent > 1 && abs(velocityX) > abs(velocityRequiredToPresent){ finish() return } let progressRequiredToPresent = 0.33 if(self.percentComplete >= CGFloat(progressRequiredToPresent)){ finish() return } cancel() case (.cancelled): self.isInteractive = false cancel() default : break } } @objc func handleDismissalGesture(_ gesture: UIScreenEdgePanGestureRecognizer) { switch(gesture.state) { case .began: self.isInteractive = true self.presentingViewController?.dismiss(animated: true, completion: nil) case .changed: let translation = gesture.translation(in: gesture.view) let transitionProgress = max(min(translation.x * tocMultiplier / self.presentedViewController!.view.bounds.maxX, 0.99), 0.01) self.update(transitionProgress) DDLogVerbose("TOC transition progress: \(transitionProgress)") case .ended: self.isInteractive = false let velocityRequiredToPresent = -gesture.view!.bounds.width * tocMultiplier let velocityRequiredToDismiss = -velocityRequiredToPresent let velocityX = gesture.velocity(in: gesture.view).x if velocityX*velocityRequiredToDismiss > 1 && abs(velocityX) > abs(velocityRequiredToDismiss){ finish() return } if velocityX*velocityRequiredToPresent > 1 && abs(velocityX) > abs(velocityRequiredToPresent){ cancel() return } let progressRequiredToDismiss = 0.50 if(self.percentComplete >= CGFloat(progressRequiredToDismiss)){ finish() return } cancel() case .cancelled: self.isInteractive = false cancel() default : break } } // MARK: - UIGestureRecognizerDelegate open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard displayMode == .modal else { return false } let isRTL = UIApplication.shared.wmf_isRTL guard (displaySide == .center) || (isRTL && displaySide == .left) || (!isRTL && displaySide == .right) else { return false } if gestureRecognizer == self.dismissalGesture { if let translation = self.dismissalGesture?.translation(in: dismissalGesture?.view) { if (translation.x * tocMultiplier > 0){ return true } else { return false } } else { return false } } else if gestureRecognizer == self.presentationGesture { let translation = presentationGesture.translation(in: presentationGesture.view) let location = presentationGesture.location(in: presentationGesture.view) let gestureWidth = presentationGesture.view!.frame.width * gesturePercentage let maxLocation: CGFloat let isInStartBoundary: Bool switch displaySide { case .left: maxLocation = gestureWidth isInStartBoundary = maxLocation - location.x > 0 default: maxLocation = presentationGesture.view!.frame.maxX - gestureWidth isInStartBoundary = location.x - maxLocation > 0 } if (translation.x * tocMultiplier < 0) && isInStartBoundary { return true } else { return false } } else { return true } } open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return otherGestureRecognizer.isKind(of: UIScreenEdgePanGestureRecognizer.self) } }
mit
airspeedswift/swift
test/IRGen/prespecialized-metadata/struct-outmodule-resilient-1argument-1distinct_use-struct-outmodule-frozen-othermodule.swift
3
1617
// RUN: %empty-directory(%t) // RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-nonfrozen-1argument.swift -emit-library -o %t/%target-library-name(Generic) -emit-module -module-name Generic -emit-module-path %t/Generic.swiftmodule -enable-library-evolution // RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-frozen-0argument.swift -emit-library -o %t/%target-library-name(Argument) -emit-module -module-name Argument -emit-module-path %t/Argument.swiftmodule -enable-library-evolution // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s -L %t -I %t -lGeneric -lArgument | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK-NOT: @"$s7Generic11OneArgumentVy0C07IntegerVGMN" = @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } import Generic import Argument // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: [[METADATA:%[0-9]+]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledName({ i32, i32 }* @"$s7Generic11OneArgumentVy0C07IntegerVGMD") // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture {{%[0-9]+}}, %swift.type* [[METADATA]]) // CHECK: } func doit() { consume( OneArgument(Integer(13)) ) } doit()
apache-2.0
rlopezdiez/RLDNavigationSwift
Classes/RLDNavigationSetup.swift
1
2749
// // RLDNavigationSwift // // Copyright (c) 2015 Rafael Lopez Diez. 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 import UIKit public struct RLDNavigationSetup { public var origin:String public var destination:String public var properties:[String:AnyObject]? public var breadcrumbs:[String]? public var navigationController:UINavigationController public init(destination:String, navigationController:UINavigationController) { self.init(destination:destination, properties:nil, breadcrumbs:nil, navigationController:navigationController) } public init(destination:String, breadcrumbs:[String]?, navigationController:UINavigationController) { self.init(destination:destination, properties:nil, breadcrumbs:breadcrumbs, navigationController:navigationController) } public init(destination:String, properties:[String:AnyObject]?, navigationController:UINavigationController) { self.init(destination:destination, properties:properties, breadcrumbs:nil, navigationController:navigationController) } public init(destination:String, properties:[String:AnyObject]?, breadcrumbs:[String]?, navigationController:UINavigationController) { let origin = NSStringFromClass(navigationController.topViewController!.dynamicType) self.init(origin:origin, destination:destination, properties:properties, breadcrumbs:breadcrumbs, navigationController:navigationController) } public init(origin:String, destination:String, properties:[String:AnyObject]?, breadcrumbs:[String]?, navigationController:UINavigationController) { self.origin = origin self.destination = destination self.properties = properties self.breadcrumbs = breadcrumbs self.navigationController = navigationController } }
apache-2.0
fuzza/SwiftyJanet
Sources/ActionServiceCallback.swift
1
840
import Foundation import RxSwift public final class ActionServiceCallback { let pipeline: SharedPipeline init(pipeline: SharedPipeline) { self.pipeline = pipeline } public func onStart<T: JanetAction>(holder: ActionHolder<T>) { pipeline.onNext( (holder, ActionState.start(holder.modified)) ) } public func onProgress<T: JanetAction>(holder: ActionHolder<T>, progress: Double) { pipeline.onNext( (holder, ActionState.progress(holder.modified, progress)) ) } public func onSuccess<T: JanetAction>(holder: ActionHolder<T>) { pipeline.onNext( (holder, ActionState.success(holder.modified)) ) } public func onError<T: JanetAction>(holder: ActionHolder<T>, error: Error) { pipeline.onNext( (holder, ActionState.error(holder.modified, error)) ) } }
mit
tubikstudio/PizzaAnimation
PizzaAnimation/Functionality/Models/TSFoodCategory.swift
1
772
// // TSDishItem.swift // PizzaAnimation // // Created by Tubik Studio on 8/4/16. // Copyright © 2016 Tubik Studio. All rights reserved. // import UIKit class TSFoodCategory { var title: String var staticImageName: String var dynamicImageName: String var color: UIColor var foodItems = [FoodItem]() init(title: String, staticImageName: String, dynamicImageName: String? = nil, color: UIColor) { self.title = title self.staticImageName = staticImageName self.color = color self.dynamicImageName = dynamicImageName == nil ? staticImageName + "_dynamic" : dynamicImageName! } } class FoodItem { var title: String init(title: String) { self.title = title } }
mit
austinzheng/swift-compiler-crashes
fixed/02256-swift-sourcefile-getcache.swift
11
226
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let b{ class a{ { } func b<H:Int } } protocol B:a{ func a
mit
yannickl/DynamicButton
Sources/DynamicButton.swift
1
9132
/* * DynamicButton * * Copyright 2015-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 UIKit /** Flat design button compounded by several lines to create several symbols like *arrows*, *checkmark*, *hamburger button*, etc. with animated transitions between each style changes. */ @IBDesignable final public class DynamicButton: UIButton { let line1Layer = CAShapeLayer() let line2Layer = CAShapeLayer() let line3Layer = CAShapeLayer() let line4Layer = CAShapeLayer() private var _style: Style = .hamburger lazy var allLayers: [CAShapeLayer] = { return [self.line1Layer, self.line2Layer, self.line3Layer, self.line4Layer] }() /** Boolean indicates whether the button can bounce when is touched. By default the value is set to true. */ public var bounceButtonOnTouch: Bool = true /** Initializes and returns a dynamic button with the specified style. You have to think to define its frame because the default one is set to {0, 0, 50, 50}. - parameter style: The style of the button. - returns: An initialized view object or nil if the object couldn't be created. */ required public init(style: Style) { super.init(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) _style = style setup() } /** Initializes and returns a newly allocated view object with the specified frame rectangle and with the Hamburger style by default. - parameter frame: The frame rectangle for the view, measured in points. The origin of the frame is relative to the superview in which you plan to add it. This method uses the frame rectangle to set the center and bounds properties accordingly. - returns: An initialized view object or nil if the object couldn't be created. */ override public init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } public override func layoutSubviews() { super.layoutSubviews() let width = bounds.width - (contentEdgeInsets.left + contentEdgeInsets.right) let height = bounds.height - (contentEdgeInsets.top + contentEdgeInsets.bottom) intrinsicSize = min(width, height) intrinsicOffset = CGPoint(x: contentEdgeInsets.left + (width - intrinsicSize) / 2, y: contentEdgeInsets.top + (height - intrinsicSize) / 2) setStyle(_style, animated: false) } public override func setTitle(_ title: String?, for state: UIControl.State) { super.setTitle("", for: state) } // MARK: - Managing the Button Setup /// Intrinsic square size var intrinsicSize = CGFloat(0) /// Intrinsic square offset var intrinsicOffset = CGPoint.zero func setup() { setTitle("", for: .normal) clipsToBounds = true addTarget(self, action: #selector(highlightAction), for: .touchDown) addTarget(self, action: #selector(highlightAction), for: .touchDragEnter) addTarget(self, action: #selector(unhighlightAction), for: .touchDragExit) addTarget(self, action: #selector(unhighlightAction), for: .touchUpInside) addTarget(self, action: #selector(unhighlightAction), for: .touchCancel) for sublayer in allLayers { layer.addSublayer(sublayer) } setupLayerPaths() } func setupLayerPaths() { for sublayer in allLayers { sublayer.fillColor = UIColor.clear.cgColor sublayer.anchorPoint = CGPoint(x: 0, y: 0) sublayer.lineJoin = CAShapeLayerLineJoin.round sublayer.lineCap = CAShapeLayerLineCap.round sublayer.contentsScale = layer.contentsScale sublayer.path = UIBezierPath().cgPath sublayer.lineWidth = lineWidth sublayer.strokeColor = strokeColor.cgColor } setStyle(_style, animated: false) } // MARK: - Configuring Buttons /// The button style. The setter is equivalent to the setStyle(, animated:) method with animated value to false. Defaults to Hamburger. public var style: Style { get { return _style } set (newValue) { setStyle(newValue, animated: false) } } /** Set the style of the button and animate the change if needed. - parameter style: The style of the button. - parameter animated: If true the transition between the old style and the new one is animated. */ public func setStyle(_ style: Style, animated: Bool) { _style = style let center = CGPoint(x: intrinsicOffset.x + intrinsicSize / 2, y: intrinsicOffset.y + intrinsicSize / 2) let buildable = style.build(center: center, size: intrinsicSize, offset: intrinsicOffset, lineWidth: lineWidth) applyButtonBuildable(buildable, animated: animated) } func applyButtonBuildable(_ buildable: DynamicButtonBuildableStyle, animated: Bool) { accessibilityValue = buildable.description for config in buildable.animationConfigurations(line1Layer, layer2: line2Layer, layer3: line3Layer, layer4: line4Layer) { if animated { let anim = animationWithKeyPath(config.keyPath, damping: 10) anim.fromValue = config.layer.path anim.toValue = config.newValue config.layer.add(anim, forKey: config.key) } else { config.layer.removeAllAnimations() } config.layer.path = config.newValue } } /// Specifies the line width used when stroking the button paths. Defaults to two. @IBInspectable public var lineWidth: CGFloat = 2 { didSet { setupLayerPaths() } } /// Specifies the color to fill the path's stroked outlines, or nil for no stroking. Defaults to black. @IBInspectable public var strokeColor: UIColor = .black { didSet { setupLayerPaths() } } /// Specifies the color to fill the path's stroked outlines when the button is highlighted, or nil to use the strokeColor. Defaults to nil. @IBInspectable public var highlightStokeColor: UIColor? = nil /// Specifies the color to fill the background when the button is highlighted, or nil to use the backgroundColor. Defaults to nil. @IBInspectable public var highlightBackgroundColor: UIColor? = nil // MARK: - Animating Buttons func animationWithKeyPath(_ keyPath: String, damping: CGFloat = 10, initialVelocity: CGFloat = 0, stiffness: CGFloat = 100) -> CABasicAnimation { guard #available(iOS 9, *) else { let basic = CABasicAnimation(keyPath: keyPath) basic.duration = 0.16 basic.fillMode = CAMediaTimingFillMode.forwards basic.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default) return basic } let spring = CASpringAnimation(keyPath: keyPath) spring.duration = spring.settlingDuration spring.damping = damping spring.initialVelocity = initialVelocity spring.stiffness = stiffness spring.fillMode = CAMediaTimingFillMode.forwards spring.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default) return spring } // MARK: - Action Methods // Store the background color color variable var defaultBackgroundColor: UIColor = .clear @objc func highlightAction() { defaultBackgroundColor = backgroundColor ?? .clear backgroundColor = highlightBackgroundColor ?? defaultBackgroundColor for sublayer in allLayers { sublayer.strokeColor = (highlightStokeColor ?? strokeColor).cgColor } if bounceButtonOnTouch { let anim = animationWithKeyPath("transform.scale", damping: 20, stiffness: 1000) anim.isRemovedOnCompletion = false anim.toValue = 1.2 layer.add(anim, forKey: "scaleup") } } @objc func unhighlightAction() { backgroundColor = defaultBackgroundColor for sublayer in allLayers { sublayer.strokeColor = strokeColor.cgColor } let anim = animationWithKeyPath("transform.scale", damping: 100, initialVelocity: 20) anim.isRemovedOnCompletion = false anim.toValue = 1 layer.add(anim, forKey: "scaledown") } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/17887-swift-typebase-getcanonicaltype.swift
11
266
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var b { class c : b protocol b { { } { } { } typealias b protocol b { " " " " { } typealias b: b
mit
eurofurence/ef-app_ios
Packages/TestUtilities/Sources/TestUtilities/Random Data Generation/Foundation/Integer+RandomValueProviding.swift
1
329
import Foundation public extension BinaryInteger { static var random: Self { return Self(UInt32.random(upperLimit: .max)) } static func random(upperLimit: UInt32) -> Self { return Self(UInt32.random(in: 0..<upperLimit)) } } extension Int: RandomValueProviding, RandomRangedValueProviding { }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/08234-swift-nominaltypedecl-getdeclaredtypeincontext.swift
11
238
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A { deinit { class A { class A<T where f: B > : A { } var f: A
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/10595-swift-sourcemanager-getmessage.swift
11
258
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension NSData { var d { struct B { enum b { func a { if true { class d { class case ,
mit
audiokit/AudioKit
Sources/AudioKit/Nodes/Playback/PhaseLockedVocoder.swift
1
8705
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AVFoundation import CAudioKit /// This is a phase locked vocoder. It has the ability to play back an audio /// file loaded into an ftable like a sampler would. Unlike a typical sampler, /// mincer allows time and pitch to be controlled separately. /// public class PhaseLockedVocoder: Node, AudioUnitContainer, Toggleable { /// Unique four-letter identifier "minc" public static let ComponentDescription = AudioComponentDescription(generator: "minc") /// Internal type of audio unit for this node public typealias AudioUnitType = InternalAU /// Internal audio unit public private(set) var internalAU: AudioUnitType? // MARK: - Parameters /// Specification for position public static let positionDef = NodeParameterDef( identifier: "position", name: "Position in time. When non-changing it will do a spectral freeze of a the current point in time.", address: akGetParameterAddress("PhaseLockedVocoderParameterPosition"), range: 0 ... 1, unit: .generic, flags: .default) /// Position in time. When non-changing it will do a spectral freeze of a the current point in time. @Parameter public var position: AUValue /// Specification for amplitude public static let amplitudeDef = NodeParameterDef( identifier: "amplitude", name: "Amplitude.", address: akGetParameterAddress("PhaseLockedVocoderParameterAmplitude"), range: 0 ... 1, unit: .generic, flags: .default) /// Amplitude. @Parameter public var amplitude: AUValue /// Specification for pitch ratio public static let pitchRatioDef = NodeParameterDef( identifier: "pitchRatio", name: "Pitch ratio. A value of. 1 normal, 2 is double speed, 0.5 is halfspeed, etc.", address: akGetParameterAddress("PhaseLockedVocoderParameterPitchRatio"), range: 0 ... 1_000, unit: .hertz, flags: .default) /// Pitch ratio. A value of. 1 normal, 2 is double speed, 0.5 is halfspeed, etc. @Parameter public var pitchRatio: AUValue // MARK: - Audio Unit /// Internal audio unit for phase locked vocoder public class InternalAU: AudioUnitBase { /// Get an array of the parameter definitions /// - Returns: Array of parameter definitions public override func getParameterDefs() -> [NodeParameterDef] { [PhaseLockedVocoder.positionDef, PhaseLockedVocoder.amplitudeDef, PhaseLockedVocoder.pitchRatioDef] } /// Create the DSP Refence for this node /// - Returns: DSP Reference public override func createDSP() -> DSPRef { akCreateDSP("PhaseLockedVocoderDSP") } } // MARK: - Initialization /// Initialize this vocoder node /// /// - Parameters: /// - file: AVAudioFile to load into memory /// - position: Position in time. When non-changing it will do a spectral freeze of a the current point in time. /// - amplitude: Amplitude. /// - pitchRatio: Pitch ratio. A value of. 1 normal, 2 is double speed, 0.5 is halfspeed, etc. /// public init( file: AVAudioFile, position: AUValue = 0, amplitude: AUValue = 1, pitchRatio: AUValue = 1 ) { super.init(avAudioNode: AVAudioNode()) instantiateAudioUnit { avAudioUnit in self.avAudioUnit = avAudioUnit self.avAudioNode = avAudioUnit guard let audioUnit = avAudioUnit.auAudioUnit as? AudioUnitType else { fatalError("Couldn't create audio unit") } self.internalAU = audioUnit self.loadFile(file) self.position = position self.amplitude = amplitude self.pitchRatio = pitchRatio } } internal func loadFile(_ avAudioFile: AVAudioFile) { Exit: do { var err: OSStatus = noErr var theFileLengthInFrames: Int64 = 0 var theFileFormat = AudioStreamBasicDescription() var thePropertySize: UInt32 = UInt32(MemoryLayout.stride(ofValue: theFileFormat)) var extRef: ExtAudioFileRef? var theData: UnsafeMutablePointer<CChar>? var theOutputFormat = AudioStreamBasicDescription() err = ExtAudioFileOpenURL(avAudioFile.url as CFURL, &extRef) if err != 0 { Log("ExtAudioFileOpenURL FAILED, Error = \(err)"); break Exit } // Get the audio data format guard let externalAudioFileRef = extRef else { break Exit } err = ExtAudioFileGetProperty(externalAudioFileRef, kExtAudioFileProperty_FileDataFormat, &thePropertySize, &theFileFormat) if err != 0 { Log("ExtAudioFileGetProperty(kExtAudioFileProperty_FileDataFormat) FAILED, Error = \(err)") break Exit } if theFileFormat.mChannelsPerFrame > 2 { Log("Unsupported Format, channel count is greater than stereo") break Exit } theOutputFormat.mSampleRate = Settings.sampleRate theOutputFormat.mFormatID = kAudioFormatLinearPCM theOutputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat theOutputFormat.mBitsPerChannel = UInt32(MemoryLayout<Float>.stride) * 8 theOutputFormat.mChannelsPerFrame = 1 // Mono theOutputFormat.mBytesPerFrame = theOutputFormat.mChannelsPerFrame * UInt32(MemoryLayout<Float>.stride) theOutputFormat.mFramesPerPacket = 1 theOutputFormat.mBytesPerPacket = theOutputFormat.mFramesPerPacket * theOutputFormat.mBytesPerFrame // Set the desired client (output) data format err = ExtAudioFileSetProperty(externalAudioFileRef, kExtAudioFileProperty_ClientDataFormat, UInt32(MemoryLayout.stride(ofValue: theOutputFormat)), &theOutputFormat) if err != 0 { Log("ExtAudioFileSetProperty(kExtAudioFileProperty_ClientDataFormat) FAILED, Error = \(err)") break Exit } // Get the total frame count thePropertySize = UInt32(MemoryLayout.stride(ofValue: theFileLengthInFrames)) err = ExtAudioFileGetProperty(externalAudioFileRef, kExtAudioFileProperty_FileLengthFrames, &thePropertySize, &theFileLengthInFrames) if err != 0 { Log("ExtAudioFileGetProperty(kExtAudioFileProperty_FileLengthFrames) FAILED, Error = \(err)") break Exit } // Read all the data into memory let dataSize = UInt32(theFileLengthInFrames) * theOutputFormat.mBytesPerFrame theData = UnsafeMutablePointer.allocate(capacity: Int(dataSize)) if theData != nil { var bufferList: AudioBufferList = AudioBufferList() bufferList.mNumberBuffers = 1 bufferList.mBuffers.mDataByteSize = dataSize bufferList.mBuffers.mNumberChannels = theOutputFormat.mChannelsPerFrame bufferList.mBuffers.mData = UnsafeMutableRawPointer(theData) // Read the data into an AudioBufferList var ioNumberFrames: UInt32 = UInt32(theFileLengthInFrames) err = ExtAudioFileRead(externalAudioFileRef, &ioNumberFrames, &bufferList) if err == noErr { // success let data = UnsafeMutablePointer<Float>( bufferList.mBuffers.mData?.assumingMemoryBound(to: Float.self) ) internalAU?.setWavetable(data: data, size: Int(ioNumberFrames)) } else { // failure theData?.deallocate() theData = nil // make sure to return NULL Log("Error = \(err)"); break Exit } } } } /// Start the node @objc open func start() { internalAU?.start() } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { internalAU?.stop() } }
mit
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Extensions/API/APIExtensions.swift
1
823
// // APIExtensions.swift // Rocket.Chat // // Created by Matheus Cardoso on 11/27/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import RealmSwift extension API { static func current(realm: Realm? = Realm.current) -> API? { guard let auth = AuthManager.isAuthenticated(realm: realm), let host = auth.apiHost?.httpServerURL() ?? auth.apiHost else { return nil } let api = API(host: host, version: Version(auth.serverVersion) ?? .zero) api.userId = auth.userId api.authToken = auth.token api.language = AppManager.language return api } static func server(index: Int) -> API? { let realm = DatabaseManager.databaseInstace(index: index) return current(realm: realm) } }
mit
MFaarkrog/Apply
Apply/Classes/Extensions/UIPickerView+Apply.swift
1
577
// // Created by Morten Faarkrog // import UIKit extension UIPickerView { @discardableResult public func apply<T: UIPickerView>(delegate: UIPickerViewDelegate?) -> T { self.delegate = delegate return self as! T } @discardableResult public func apply<T: UIPickerView>(dataSource: UIPickerViewDataSource) -> T { self.dataSource = dataSource return self as! T } @discardableResult public func apply<T: UIPickerView>(showsSelectionIndicator: Bool) -> T { self.showsSelectionIndicator = showsSelectionIndicator return self as! T } }
mit
auth0/Lock.iOS-OSX
Lock/ClassicRouter.swift
1
10317
// ClassicRouter.swift // // Copyright (c) 2016 Auth0 (http://auth0.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 import Auth0 struct ClassicRouter: Router { weak var controller: LockViewController? let user = User() let lock: Lock var observerStore: ObserverStore { return self.lock.observerStore } init(lock: Lock, controller: LockViewController) { self.controller = controller self.lock = lock } var root: Presentable? { let connections = self.lock.connections guard !connections.isEmpty else { self.lock.logger.debug("No connections configured. Loading application info from Auth0...") let baseURL = self.lock.options.configurationBaseURL ?? self.lock.authentication.url let interactor = CDNLoaderInteractor(baseURL: baseURL, clientId: self.lock.authentication.clientId) return ConnectionLoadingPresenter(loader: interactor, navigator: self, dispatcher: lock.observerStore, options: self.lock.options) } let whitelistForActiveAuth = self.lock.options.enterpriseConnectionUsingActiveAuth switch (connections.database, connections.oauth2, connections.enterprise) { // Database root case (.some(let database), let oauth2, let enterprise): guard self.lock.options.allow != [.ResetPassword] && self.lock.options.initialScreen != .resetPassword else { return forgotPassword } let authentication = self.lock.authentication let webAuthInteractor = Auth0OAuth2Interactor(authentication: self.lock.authentication, dispatcher: lock.observerStore, options: self.lock.options, nativeHandlers: self.lock.nativeHandlers) let interactor = DatabaseInteractor(connection: database, authentication: authentication, webAuthentication: webAuthInteractor, user: self.user, options: self.lock.options, dispatcher: lock.observerStore) let presenter = DatabasePresenter(interactor: interactor, connection: database, navigator: self, options: self.lock.options) if !oauth2.isEmpty { let interactor = Auth0OAuth2Interactor(authentication: self.lock.authentication, dispatcher: lock.observerStore, options: self.lock.options, nativeHandlers: self.lock.nativeHandlers) presenter.authPresenter = AuthPresenter(connections: oauth2, interactor: interactor, customStyle: self.lock.style.oauth2) } if !enterprise.isEmpty { let authInteractor = Auth0OAuth2Interactor(authentication: self.lock.authentication, dispatcher: lock.observerStore, options: self.lock.options, nativeHandlers: self.lock.nativeHandlers) let interactor = EnterpriseDomainInteractor(connections: connections, user: self.user, authentication: authInteractor) presenter.enterpriseInteractor = interactor } return presenter // Single Enterprise with active auth support (e.g. AD) case (nil, let oauth2, let enterprise) where oauth2.isEmpty && enterprise.hasJustOne(andIn: whitelistForActiveAuth): guard let connection = enterprise.first else { return nil } return enterpriseActiveAuth(connection: connection, domain: connection.domains.first) // Single Enterprise with support for passive auth only (web auth) and some social connections case (nil, let oauth2, let enterprise) where enterprise.hasJustOne(andNotIn: whitelistForActiveAuth): guard let connection = enterprise.first else { return nil } let authInteractor = Auth0OAuth2Interactor(authentication: self.lock.authentication, dispatcher: lock.observerStore, options: self.lock.options, nativeHandlers: self.lock.nativeHandlers) let connections: [OAuth2Connection] = oauth2 + [connection] return AuthPresenter(connections: connections, interactor: authInteractor, customStyle: self.lock.style.oauth2) // Social connections only case (nil, let oauth2, let enterprise) where enterprise.isEmpty: let interactor = Auth0OAuth2Interactor(authentication: self.lock.authentication, dispatcher: lock.observerStore, options: self.lock.options, nativeHandlers: self.lock.nativeHandlers) let presenter = AuthPresenter(connections: oauth2, interactor: interactor, customStyle: self.lock.style.oauth2) return presenter // Multiple enterprise connections and maybe some social case (nil, let oauth2, let enterprise) where !enterprise.isEmpty: let authInteractor = Auth0OAuth2Interactor(authentication: self.lock.authentication, dispatcher: lock.observerStore, options: self.lock.options, nativeHandlers: self.lock.nativeHandlers) let interactor = EnterpriseDomainInteractor(connections: connections, user: self.user, authentication: authInteractor) let presenter = EnterpriseDomainPresenter(interactor: interactor, navigator: self, options: self.lock.options) if !oauth2.isEmpty { presenter.authPresenter = AuthPresenter(connections: connections.oauth2, interactor: authInteractor, customStyle: self.lock.style.oauth2) } return presenter // Not supported connections configuration default: return nil } } var forgotPassword: Presentable? { let connections = self.lock.connections guard !connections.isEmpty else { exit(withError: UnrecoverableError.clientWithNoConnections) return nil } let interactor = DatabasePasswordInteractor(connections: connections, authentication: self.lock.authentication, user: self.user, dispatcher: lock.observerStore) let presenter = DatabaseForgotPasswordPresenter(interactor: interactor, connections: connections, navigator: self, options: self.lock.options) presenter.customLogger = self.lock.logger return presenter } func multifactor(withToken mfaToken: String? = nil) -> Presentable? { let connections = self.lock.connections guard let database = connections.database else { exit(withError: UnrecoverableError.missingDatabaseConnection) return nil } let authentication = self.lock.authentication let interactor = MultifactorInteractor(user: self.user, authentication: authentication, connection: database, options: self.lock.options, dispatcher: lock.observerStore, mfaToken: mfaToken) let presenter = MultifactorPresenter(interactor: interactor, connection: database, navigator: self) presenter.customLogger = self.lock.logger return presenter } func enterpriseActiveAuth(connection: EnterpriseConnection, domain: String?) -> Presentable? { let authentication = self.lock.authentication let interactor = EnterpriseActiveAuthInteractor(connection: connection, authentication: authentication, user: self.user, options: self.lock.options, dispatcher: lock.observerStore) let presenter = EnterpriseActiveAuthPresenter(interactor: interactor, options: self.lock.options, domain: domain) presenter.customLogger = self.lock.logger return presenter } func onBack() { guard let current = self.controller?.routes.back() else { return } self.user.reset() let style = self.lock.style self.lock.logger.debug("Back pressed. Showing \(current)") switch current { case .forgotPassword: self.controller?.present(self.forgotPassword, title: current.title(withStyle: style)) case .root: self.controller?.present(self.root, title: style.hideTitle ? nil : style.title) default: break } } func navigate(_ route: Route) { let presentable: Presentable? switch route { case .root where self.controller?.routes.current != .root: presentable = self.root case .forgotPassword: presentable = self.forgotPassword case .multifactor: presentable = self.multifactor() case .multifactorWithToken(let token): presentable = self.multifactor(withToken: token) case .enterpriseActiveAuth(let connection, let domain): presentable = self.enterpriseActiveAuth(connection: connection, domain: domain) case .unrecoverableError(let error): presentable = self.unrecoverableError(for: error) default: self.lock.logger.warn("Ignoring navigation \(route)") return } self.lock.logger.debug("Navigating to \(route)") self.controller?.routes.go(route) self.controller?.present(presentable, title: route.title(withStyle: self.lock.style)) } } private extension Array where Element: OAuth2Connection { func hasJustOne(andIn list: [String]) -> Bool { guard let connection = self.first, self.count == 1 else { return false } return list.contains(connection.name) } func hasJustOne(andNotIn list: [String]) -> Bool { guard let connection = self.first, self.count == 1 else { return false } return !list.contains(connection.name) } }
mit
LacieJiang/DatePickerWithToolBar
DatePickerWithToolBar/DatePickerWithToolBar/ViewController.swift
1
521
// // ViewController.swift // DatePickerWithToolBar // // Created by liyinjiang on 7/25/14. // Copyright (c) 2014 liyinjiang. All rights reserved. // import UIKit class ViewController: UIViewController { 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
avaidyam/Parrot
MochaUI/PreviewController.swift
1
9174
import AppKit import Mocha import Quartz /* TODO: NSPopover.title/addTitlebar(animated: ...)? */ /* TODO: Use NSPressGestureRecognizer if no haptic support. */ /* TODO: Maybe support tear-off popover-windows? */ //let preview = PreviewController(for: self.view, with: .file(URL(fileURLWithPath: pathToFile), nil)) //preview.delegate = self // not required /// Provides content for a `PreviewController` dynamically. public protocol PreviewControllerDelegate: class { /// Return the content for the previewing controller, depending on where /// the user began the previewing within the `parentView`. If `nil` is /// returned from this method, previewing is disabled. func previewController(_: PreviewController, contentAtPoint: CGPoint) -> PreviewController.ContentType? } /// The `PreviewController` handles user interactions with previewing indications. /// The functionality is similar to dictionary or Safari link force touch lookup. public class PreviewController: NSObject, NSPopoverDelegate, NSGestureRecognizerDelegate { /// Describes the content to be previewed by the controller for a given interaction. public enum ContentType { /// case view(NSViewController) /// The content is a `file://` URL, optionally with a preview size. /// If no size is specified (`nil`), `PreviewController.defaultSize` is used. case file(URL, CGSize?) } /// If no size is provided for a `ContentType.file(_, _)`, this value is used. public static var defaultSize = CGSize(width: 512, height: 512) /// Create a `QLPreviewView`-containing `NSViewController` to support files. private static func previewer(for item: QLPreviewItem, size: CGSize?) -> NSViewController { let vc = NSViewController() let rect = NSRect(origin: .zero, size: size ?? PreviewController.defaultSize) let ql = QLPreviewView(frame: rect, style: .normal)! ql.previewItem = item vc.view = ql return vc } /// If the `delegate` is not set, the `content` set will be used for previewing, /// applicable to the whole `bounds` of the `parentView`. /// /// If both `delegate` and `content` are `nil`, previewing is disabled. public var content: ContentType? = nil /// Provides content for previewing controller dynamically. /// /// If both `delegate` and `content` are `nil`, previewing is disabled. public weak var delegate: PreviewControllerDelegate? = nil /// The view that should be registered for previewing; this is not the view /// that is contained within the preview itself. public weak var parentView: NSView? = nil { willSet { self.parentView?.removeGestureRecognizer(self.gesture) } didSet { self.parentView?.addGestureRecognizer(self.gesture) } } /// Whether the user is currently interacting the preview; that is, the user /// is engaged in a force touch interaction to display the preview. public private(set) var interacting: Bool = false /// Whether the preview is visible; setting this property manually bypasses /// the user interaction to display the preview regardless. /// /// When setting `isVisible = true`, the `delegate` is not consulted. Use /// `content` to specify the preview content. /// /// Setting `isVisible` while the user is currently interacting is a no-op. public var isVisible: Bool { get { return self.popover.isShown } set { switch newValue { case false: guard self.popover.isShown, !self.interacting else { return } self.popover.performClose(nil) case true: guard !self.popover.isShown, !self.interacting else { return } guard let view = self.parentView else { fatalError("PreviewController.parentView was not set, isVisible=true failed.") } guard let content = self.content else { return } // Set the contentView here to maintain only a short-term reference. switch content { case .view(let vc): self.popover.contentViewController = vc case .file(let url, let size): self.popover.contentViewController = PreviewController.previewer(for: url as NSURL, size: size) } self.popover.show(relativeTo: view.bounds, of: view, preferredEdge: .minY) } } } /// The popover used to contain and animate the preview content. private lazy var popover: NSPopover = { let popover = NSPopover() popover.behavior = .semitransient popover.delegate = self //popover.positioningOptions = .keepTopStable return popover }() /// The gesture recognizer used to handle user interaction for previewing. private lazy var gesture: PressureGestureRecognizer = { let gesture = PressureGestureRecognizer(target: self, action: #selector(self.gesture(_:))) gesture.delegate = self //gesture.behavior = .primaryAccelerator return gesture }() /// Create a `PreviewController` with a provided `parentView` and `content`. public init(for view: NSView? = nil, with content: ContentType? = nil) { super.init() self.commonInit(view, content) // rebound to call property observers } private func commonInit(_ view: NSView? = nil, _ content: ContentType? = nil) { self.parentView = view self.content = content } @objc dynamic private func gesture(_ sender: PressureGestureRecognizer) { switch sender.state { case .possible: break // ignore case .began: guard !self.popover.isShown, !self.interacting else { return } // Begin interaction animation: self.interacting = true let point = sender.location(in: self.parentView) self.popover._private._beginPredeepAnimationAgainstPoint(point, inView: self.parentView) case .changed: guard self.popover.isShown, self.interacting else { return } // Update interaction animation, unless stage 2 (deep press): guard sender.stage != 2 else { fallthrough } self.popover._private._doPredeepAnimation(withProgress: Double(sender.stage == 2 ? 1.0 : sender.pressure)) case .ended: guard self.popover.isShown, self.interacting else { return } // Complete interaction animation, only if stage 2 (deep press): guard sender.stage == 2 else { fallthrough } self.interacting = false self.popover._private._completeDeepAnimation() case .failed, .cancelled: guard self.popover.isShown, self.interacting else { return } // Cancel interaction animation: self.interacting = false self.popover._private._cancelPredeepAnimation() } } public func popoverDidClose(_ notification: Notification) { self.interacting = false // Clear the contentView here to maintain only a short-term reference. self.popover.contentViewController = nil } public func gestureRecognizerShouldBegin(_ sender: NSGestureRecognizer) -> Bool { /// If there exists a `delegate`, request its dynamic content. /// Otherwise, possibly use the static `content` property. func effectiveContent(_ point: CGPoint) -> ContentType? { guard let delegate = self.delegate else { return self.content } return delegate.previewController(self, contentAtPoint: point) } // Because `self.popover.behavior = .semitransient`, if the preview is // currently visible, allow the click to passthrough to the `parentView`. // This allows the "second click" to be the actual commit action. guard !self.popover.isShown else { return false } let content = effectiveContent(sender.location(in: self.parentView)) guard content != nil else { return false } // Set the contentView here to maintain only a short-term reference. switch content! { case .view(let vc): self.popover.contentViewController = vc case .file(let url, let size): self.popover.contentViewController = PreviewController.previewer(for: url as NSURL, size: size) } return true } // TODO: /* public func gestureRecognizer(_ sender: NSGestureRecognizer, shouldAttemptToRecognizeWith event: NSEvent) -> Bool { if sender is NSPressGestureRecognizer { return !event.associatedEventsMask.contains(.pressure) } else if sender is PressureGestureRecognizer { return event.associatedEventsMask.contains(.pressure) } return false } */ }
mpl-2.0
ReiVerdugo/uikit-fundamentals
Roshambo App/Roshambo App/ViewController.swift
1
1535
// // ViewController.swift // Roshambo App // // Created by Reinaldo Verdugo on 8/10/16. // Copyright © 2016 Reinaldo Verdugo. All rights reserved. // import UIKit enum Move : Int { case Rock = 0 case Paper case Scissors } class ViewController: UIViewController { func generateRandomMove () -> Move { let value = Int(arc4random_uniform(3)) return Move(rawValue: value)! } @IBAction func rockAction(_ sender: AnyObject) { let nextController = storyboard?.instantiateViewController(withIdentifier: "second") as! SecondViewController nextController.playerMove = .Rock nextController.opponentMove = generateRandomMove() // present(nextController, animated: true, completion: nil) self.navigationController?.pushViewController(nextController, animated: true) } @IBAction func paperAction(_ sender: AnyObject) { performSegue(withIdentifier: "paperAction", sender: self) } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let nextController = segue.destination as! SecondViewController nextController.opponentMove = generateRandomMove() if segue.identifier == "paperAction" { nextController.playerMove = .Paper } else if segue.identifier == "scissorsAction" { nextController.playerMove = .Scissors } } }
mit
kang77649119/DouYuDemo
DouYuDemo/DouYuDemo/Classes/Tools/Constant.swift
1
432
// // Constant.swift // DouYuDemo // // Created by 也许、 on 16/10/7. // Copyright © 2016年 K. All rights reserved. // import UIKit // 屏幕宽高 let screenW = UIScreen.main.bounds.width let screenH = UIScreen.main.bounds.height // 状态栏高度 let statusBarH:CGFloat = 20.0 // 导航栏高度 let navBarH:CGFloat = 44.0 // 底部工具栏高度 let tabBarH:CGFloat = 44.0 // 菜单高度 let menuH:CGFloat = 35
mit
mirego/PinLayout
Example/PinLayoutSample/UI/Menu/MenuViewController.swift
1
5232
// Copyright (c) 2017 Luc Dion // 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 enum PageType: Int { case intro case adjustToContainer case tableView case collectionView case animations case autoAdjustingSize case safeArea case relativePositions case between case form case wrapContent case autoSizing case tableViewWithReadable case introRTL case introObjC case count var title: String { switch self { case .intro: return "Introduction Example" case .adjustToContainer: return "Adjust to Container Size" case .tableView: return "UITableView with Variable Cell's Height" case .collectionView: return "UICollectionView Example" case .animations: return "Animation Example" case .autoAdjustingSize: return "Auto Adjusting Size" case .safeArea: return "SafeArea & readableMargins" case .relativePositions: return "Relative Positioning" case .between: return "Between Example" case .form: return "Form Example" case .wrapContent: return "wrapContent Example" case .autoSizing: return "Auto Sizing" case .tableViewWithReadable: return "UITableView using readableMargins" case .introRTL: return "Right-to-left Language Support" case .introObjC: return "Objective-C PinLayout Example" case .count: return "" } } var viewController: UIViewController { switch self { case .intro: return IntroViewController(pageType: self) case .adjustToContainer: return AdjustToContainerViewController(pageType: self) case .tableView: return TableViewExampleViewController(pageType: self) case .collectionView: return CollectionViewExampleViewController(pageType: self) case .safeArea: let tabbarController = UITabBarController() tabbarController.title = self.title tabbarController.setViewControllers([SafeAreaViewController(), SafeAreaAndMarginsViewController()], animated: false) return tabbarController case .animations: return AnimationsViewController(pageType: self) case .autoAdjustingSize: return AutoAdjustingSizeViewController(pageType: self) case .relativePositions: return RelativeViewController(pageType: self) case .between: return BetweenViewController(pageType: self) case .form: return FormViewController(pageType: self) case .wrapContent: return WrapContentViewController(pageType: self) case .autoSizing: return AutoSizingViewController() case .tableViewWithReadable: return TableViewReadableContentViewController(pageType: self) case .introRTL: return IntroRTLViewController(pageType: self) case .introObjC: return IntroObjectiveCViewController() case .count: return UIViewController() } } } class MenuViewController: UIViewController { private var mainView: MenuView { return self.view as! MenuView } init() { super.init(nibName: nil, bundle: nil) title = "PinLayout Examples" navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { view = MenuView() mainView.delegate = self } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) // didSelect(pageType: .intro) } } // MARK: MenuViewDelegate extension MenuViewController: MenuViewDelegate { func didSelect(pageType: PageType) { navigationController?.pushViewController(pageType.viewController, animated: true) } }
mit
abdullahselek/DragDropUI
DragDropUITests/DDImageViewTests.swift
1
2700
// // DDImageViewTests.swift // DragDropUI // // Copyright © 2016 Abdullah Selek. All rights reserved. // // 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 Quick import Nimble @testable import DragDropUI class DDImageViewTests: QuickSpec { override func spec() { describe("DDImageView Tests", { var imageView: DDImageView! var viewController: UIViewController! beforeEach { imageView = DDImageView(frame: CGRect(x: 0.0, y: 0.0, width: 200.0, height: 40.0)) viewController = UIViewController() } describe(".init(frame:)", { it("should initiate successfully", closure: { expect(imageView).notTo(beNil()) }) }) describe(".didMoveToSuperview()", { context("when superview not nil", { beforeEach { viewController.view.addSubview(imageView) let _ = viewController.view } it("should have gesture recognizers", closure: { expect(imageView.gestureRecognizers).to(haveCount(2)) }) }) context("when superview nil", { beforeEach { imageView.didMoveToSuperview() } it("should not have gesture recognizers", closure: { expect(imageView.gestureRecognizers).to(beNil()) }) }) }) }) } }
mit
karivalkama/Agricola-Scripture-Editor
TranslationEditor/TopBarUIView.swift
1
3859
// // TopBarUIView.swift // TranslationEditor // // Created by Mikko Hilpinen on 19.5.2017. // Copyright © 2017 SIL. All rights reserved. // import UIKit // This view is used for basic navigation and info display on multiple different views // The bar also provides access to P2P and other sharing options @IBDesignable class TopBarUIView: CustomXibView { // OUTLETS ------------------ @IBOutlet weak var leftSideButton: UIButton! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var userView: TopUserView! // ATTRIBUTES -------------- // This will be called each time connection view is closed var connectionCompletionHandler: (() -> ())? private weak var viewController: UIViewController? private var leftSideAction: (() -> ())? private var avatar: Avatar? private var info: AvatarInfo? // LOAD ---------------------- override init(frame: CGRect) { super.init(frame: frame) setupXib(nibName: "TopBar") } required init?(coder: NSCoder) { super.init(coder: coder) setupXib(nibName: "TopBar") } // ACTIONS ------------------ @IBAction func leftSideButtonPressed(_ sender: Any) { leftSideAction?() } @IBAction func connectButtonPressed(_ sender: Any) { guard let viewController = viewController else { print("ERROR: Cannot display connect VC without a view controller") return } performConnect(using: viewController) } @IBAction func userViewTapped(_ sender: Any) { guard let viewController = viewController else { print("ERROR: Cannot display user view without a view controller") return } guard let avatar = avatar, let info = info else { print("ERROR: No user data to edit") return } viewController.displayAlert(withIdentifier: EditAvatarVC.identifier, storyBoardId: "MainMenu") { ($0 as! EditAvatarVC).configureForEdit(avatar: avatar, avatarInfo: info) { _, _ in self.updateUserView() } } } // OTHER METHODS -------------- // Localisation added automatically func configure(hostVC: UIViewController, title: String, leftButtonText: String? = nil, leftButtonAction: (() -> ())? = nil) { viewController = hostVC titleLabel.text = NSLocalizedString(title, comment: "A title shown in the top bar") if let leftButtonText = leftButtonText.map({ NSLocalizedString($0, comment: "A button text in the top bar") }) { leftSideButton.setTitle(leftButtonText, for: .normal) leftSideButton.isHidden = false self.leftSideAction = leftButtonAction leftSideButton.isEnabled = leftButtonAction != nil } else { leftSideButton.isHidden = true } updateUserView() } func setLeftButtonAction(_ action: @escaping () -> ()) { leftSideAction = action leftSideButton.isEnabled = true } func performConnect(using viewController: UIViewController) { if let completionHandler = connectionCompletionHandler { viewController.displayAlert(withIdentifier: ConnectionVC.identifier, storyBoardId: "Common") { ($0 as! ConnectionVC).configure(completion: completionHandler) } } else { viewController.displayAlert(withIdentifier: ConnectionVC.identifier, storyBoardId: "Common") } } func updateUserView() { var foundUserData = false // Sets up the user view if let projectId = Session.instance.projectId, let avatarId = Session.instance.avatarId { do { if let project = try Project.get(projectId), let avatar = try Avatar.get(avatarId), let info = try avatar.info() { self.avatar = avatar self.info = info userView.configure(projectName: project.name, username: avatar.name, image: info.image ?? #imageLiteral(resourceName: "userIcon")) foundUserData = true } } catch { print("ERROR: Failed to load user information for the top bar. \(error)") } } userView.isHidden = !foundUserData } }
mit
ArshAulakh59/ArchitectureSample
ArchitectureSample/CustomManagement/ViewModels/DogsDataSource.swift
1
1095
// // DogsDataSource.swift // ArchitectureSample // // Created by Arsh Aulakh on 2016-10-16. // Copyright © 2016 Bhouse. All rights reserved. // import UIKit class DogsDataSource: NSObject, DataSourceProtocol { internal var title: String { return Pet.Dogs.value } } extension DogsDataSource { //MARK: Configure Table func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 81 } @objc(tableView:cellForRowAtIndexPath:) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UITableViewCell.self)) as UITableViewCell? if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: String(describing: UITableView.self)) } cell?.textLabel?.text = "Dog \(indexPath.row)" return cell! } @objc(tableView:didSelectRowAtIndexPath:) func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } }
mit
zisko/swift
stdlib/public/core/ValidUTF8Buffer.swift
1
6965
//===--- ValidUTF8Buffer.swift - Bounded Collection of Valid UTF-8 --------===// // // 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 // //===----------------------------------------------------------------------===// // // Stores valid UTF8 inside an unsigned integer. // // Actually this basic type could be used to store any UInt8s that cannot be // 0xFF // //===----------------------------------------------------------------------===// @_fixed_layout public struct _ValidUTF8Buffer<Storage: UnsignedInteger & FixedWidthInteger> { public typealias Element = Unicode.UTF8.CodeUnit internal typealias _Storage = Storage @_versioned internal var _biasedBits: Storage @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_biasedBits: Storage) { self._biasedBits = _biasedBits } @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_containing e: Element) { _sanityCheck( e != 192 && e != 193 && !(245...255).contains(e), "invalid UTF8 byte") _biasedBits = Storage(truncatingIfNeeded: e &+ 1) } } extension _ValidUTF8Buffer : Sequence { public typealias SubSequence = Slice<_ValidUTF8Buffer> @_fixed_layout // FIXME(sil-serialize-all) public struct Iterator : IteratorProtocol, Sequence { @_inlineable // FIXME(sil-serialize-all) public init(_ x: _ValidUTF8Buffer) { _biasedBits = x._biasedBits } @_inlineable // FIXME(sil-serialize-all) public mutating func next() -> Element? { if _biasedBits == 0 { return nil } defer { _biasedBits >>= 8 } return Element(truncatingIfNeeded: _biasedBits) &- 1 } @_versioned // FIXME(sil-serialize-all) internal var _biasedBits: Storage } @_inlineable // FIXME(sil-serialize-all) public func makeIterator() -> Iterator { return Iterator(self) } } extension _ValidUTF8Buffer : Collection { @_fixed_layout // FIXME(sil-serialize-all) public struct Index : Comparable { @_versioned internal var _biasedBits: Storage @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_biasedBits: Storage) { self._biasedBits = _biasedBits } @_inlineable // FIXME(sil-serialize-all) public static func == (lhs: Index, rhs: Index) -> Bool { return lhs._biasedBits == rhs._biasedBits } @_inlineable // FIXME(sil-serialize-all) public static func < (lhs: Index, rhs: Index) -> Bool { return lhs._biasedBits > rhs._biasedBits } } @_inlineable // FIXME(sil-serialize-all) public var startIndex : Index { return Index(_biasedBits: _biasedBits) } @_inlineable // FIXME(sil-serialize-all) public var endIndex : Index { return Index(_biasedBits: 0) } @_inlineable // FIXME(sil-serialize-all) public var count : Int { return Storage.bitWidth &>> 3 &- _biasedBits.leadingZeroBitCount &>> 3 } @_inlineable // FIXME(sil-serialize-all) public var isEmpty : Bool { return _biasedBits == 0 } @_inlineable // FIXME(sil-serialize-all) public func index(after i: Index) -> Index { _debugPrecondition(i._biasedBits != 0) return Index(_biasedBits: i._biasedBits >> 8) } @_inlineable // FIXME(sil-serialize-all) public subscript(i: Index) -> Element { return Element(truncatingIfNeeded: i._biasedBits) &- 1 } } extension _ValidUTF8Buffer : BidirectionalCollection { @_inlineable // FIXME(sil-serialize-all) public func index(before i: Index) -> Index { let offset = _ValidUTF8Buffer(_biasedBits: i._biasedBits).count _debugPrecondition(offset != 0) return Index(_biasedBits: _biasedBits &>> (offset &<< 3 - 8)) } } extension _ValidUTF8Buffer : RandomAccessCollection { public typealias Indices = DefaultIndices<_ValidUTF8Buffer> @_inlineable // FIXME(sil-serialize-all) @inline(__always) public func distance(from i: Index, to j: Index) -> Int { _debugPrecondition(_isValid(i)) _debugPrecondition(_isValid(j)) return ( i._biasedBits.leadingZeroBitCount - j._biasedBits.leadingZeroBitCount ) &>> 3 } @_inlineable // FIXME(sil-serialize-all) @inline(__always) public func index(_ i: Index, offsetBy n: Int) -> Index { let startOffset = distance(from: startIndex, to: i) let newOffset = startOffset + n _debugPrecondition(newOffset >= 0) _debugPrecondition(newOffset <= count) return Index(_biasedBits: _biasedBits._fullShiftRight(newOffset &<< 3)) } } extension _ValidUTF8Buffer : RangeReplaceableCollection { @_inlineable // FIXME(sil-serialize-all) public init() { _biasedBits = 0 } @_inlineable // FIXME(sil-serialize-all) public var capacity: Int { return _ValidUTF8Buffer.capacity } @_inlineable // FIXME(sil-serialize-all) public static var capacity: Int { return Storage.bitWidth / Element.bitWidth } @_inlineable // FIXME(sil-serialize-all) @inline(__always) public mutating func append(_ e: Element) { _debugPrecondition(count + 1 <= capacity) _sanityCheck( e != 192 && e != 193 && !(245...255).contains(e), "invalid UTF8 byte") _biasedBits |= Storage(e &+ 1) &<< (count &<< 3) } @_inlineable // FIXME(sil-serialize-all) @inline(__always) @discardableResult public mutating func removeFirst() -> Element { _debugPrecondition(!isEmpty) let result = Element(truncatingIfNeeded: _biasedBits) &- 1 _biasedBits = _biasedBits._fullShiftRight(8) return result } @_inlineable // FIXME(sil-serialize-all) @_versioned internal func _isValid(_ i: Index) -> Bool { return i == endIndex || indices.contains(i) } @_inlineable // FIXME(sil-serialize-all) @inline(__always) public mutating func replaceSubrange<C: Collection>( _ target: Range<Index>, with replacement: C ) where C.Element == Element { _debugPrecondition(_isValid(target.lowerBound)) _debugPrecondition(_isValid(target.upperBound)) var r = _ValidUTF8Buffer() for x in self[..<target.lowerBound] { r.append(x) } for x in replacement { r.append(x) } for x in self[target.upperBound...] { r.append(x) } self = r } } extension _ValidUTF8Buffer { @_inlineable // FIXME(sil-serialize-all) @inline(__always) public mutating func append<T>(contentsOf other: _ValidUTF8Buffer<T>) { _debugPrecondition(count + other.count <= capacity) _biasedBits |= Storage( truncatingIfNeeded: other._biasedBits) &<< (count &<< 3) } } extension _ValidUTF8Buffer { @_inlineable // FIXME(sil-serialize-all) public static var encodedReplacementCharacter : _ValidUTF8Buffer { return _ValidUTF8Buffer(_biasedBits: 0xBD_BF_EF &+ 0x01_01_01) } }
apache-2.0
samantharachelb/todolist
todolistUITests/todolistUITests.swift
1
1288
// // todolistUITests.swift // todolistUITests // // Created by Samantha Emily-Rachel Belnavis on 2017-10-02. // Copyright © 2017 Samantha Emily-Rachel Belnavis. All rights reserved. // import XCTest class todolistUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
mcjg/MGAFoundation
Example/MGAFoundation/AppDelegate.swift
1
2150
// // AppDelegate.swift // MGAFoundation // // Created by Matt Green on 09/22/2015. // Copyright (c) 2015 Matt Green. All rights reserved. // import UIKit @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:. } }
mit
OscarSwanros/swift
test/decl/enum/enumtest.swift
5
8569
// RUN: %target-typecheck-verify-swift //===----------------------------------------------------------------------===// // Tests for various simple enum constructs //===----------------------------------------------------------------------===// public enum unionSearchFlags { case none case backwards case anchored init() { self = .none } } func test1() -> unionSearchFlags { let _ : unionSearchFlags var b = unionSearchFlags.none b = unionSearchFlags.anchored _ = b return unionSearchFlags.backwards } func test1a() -> unionSearchFlags { var _ : unionSearchFlags var b : unionSearchFlags = .none b = .anchored _ = b // ForwardIndex use of MaybeInt. _ = MaybeInt.none return .backwards } func test1b(_ b : Bool) { _ = 123 _ = .description == 1 // expected-error {{ambiguous reference to member '=='}} } enum MaybeInt { case none case some(Int) // expected-note {{did you mean 'some'?}} init(_ i: Int) { self = MaybeInt.some(i) } } func test2(_ a: Int, _ b: Int, _ c: MaybeInt) { _ = MaybeInt.some(4) _ = MaybeInt.some _ = MaybeInt.some(b) test2(1, 2, .none) } enum ZeroOneTwoThree { case Zero case One(Int) case Two(Int, Int) case Three(Int,Int,Int) case Unknown(MaybeInt, MaybeInt, MaybeInt) init (_ i: Int) { self = .One(i) } init (_ i: Int, _ j: Int, _ k: Int) { self = .Three(i, j, k) } init (_ i: MaybeInt, _ j: MaybeInt, _ k: MaybeInt) { self = .Unknown(i, j, k) } } func test3(_ a: ZeroOneTwoThree) { _ = ZeroOneTwoThree.Three(1,2,3) _ = ZeroOneTwoThree.Unknown( MaybeInt.none, MaybeInt.some(4), MaybeInt.some(32)) _ = ZeroOneTwoThree(MaybeInt.none, MaybeInt(4), MaybeInt(32)) var _ : Int = ZeroOneTwoThree.Zero // expected-error {{cannot convert value of type 'ZeroOneTwoThree' to specified type 'Int'}} // expected-warning @+1 {{unused}} test3 ZeroOneTwoThree.Zero // expected-error {{expression resolves to an unused function}} expected-error{{consecutive statements}} {{8-8=;}} test3 (ZeroOneTwoThree.Zero) test3(ZeroOneTwoThree.Zero) test3 // expected-error {{expression resolves to an unused function}} // expected-warning @+1 {{unused}} (ZeroOneTwoThree.Zero) var _ : ZeroOneTwoThree = .One(4) var _ : (Int,Int) -> ZeroOneTwoThree = .Two // expected-error{{type '(Int, Int) -> ZeroOneTwoThree' has no member 'Two'}} var _ : Int = .Two // expected-error{{type 'Int' has no member 'Two'}} var _ : MaybeInt = 0 > 3 ? .none : .soma(3) // expected-error {{type 'MaybeInt' has no member 'soma'}} } func test3a(_ a: ZeroOneTwoThree) { var e : ZeroOneTwoThree = (.Three(1, 2, 3)) var f = ZeroOneTwoThree.Unknown(.none, .some(4), .some(32)) var g = .none // expected-error {{reference to member 'none' cannot be resolved without a contextual type}} // Overload resolution can resolve this to the right constructor. var h = ZeroOneTwoThree(1) var i = 0 > 3 ? .none : .some(3) // expected-error {{reference to member 'none' cannot be resolved without a contextual type}} test3a; // expected-error {{unused function}} .Zero // expected-error {{reference to member 'Zero' cannot be resolved without a contextual type}} test3a // expected-error {{unused function}} (.Zero) // expected-error {{reference to member 'Zero' cannot be resolved without a contextual type}} test3a(.Zero) } struct CGPoint { var x : Int, y : Int } typealias OtherPoint = (x : Int, y : Int) func test4() { var a : CGPoint // Note: we reject the following because it conflicts with the current // "init" hack. var b = CGPoint.CGPoint(1, 2) // expected-error {{type 'CGPoint' has no member 'CGPoint'}} var c = CGPoint(x: 2, y : 1) // Using injected name. var e = CGPoint.x // expected-error {{member 'x' cannot be used on type 'CGPoint'}} var f = OtherPoint.x // expected-error {{type 'OtherPoint' (aka '(x: Int, y: Int)') has no member 'x'}} } struct CGSize { var width : Int, height : Int } extension CGSize { func area() -> Int { return width*self.height } func area_wrapper() -> Int { return area() } } struct CGRect { var origin : CGPoint, size : CGSize func area() -> Int { return self.size.area() } } func area(_ r: CGRect) -> Int { return r.size.area() } extension CGRect { func search(_ x: Int) -> CGSize {} func bad_search(_: Int) -> CGSize {} } func test5(_ myorigin: CGPoint) { let x1 = CGRect(origin: myorigin, size: CGSize(width: 42, height: 123)) let x2 = x1 _ = 4+5 // Dot syntax. _ = x2.origin.x _ = x1.size.area() _ = (r : x1.size).r.area() _ = x1.size.area() _ = (r : x1.size).r.area() _ = x1.area _ = x1.search(42) _ = x1.search(42).width // TODO: something like this (name binding on the LHS): // var (CGSize(width, height)) = CGSize(1,2) // TODO: something like this, how do we get it in scope in the {} block? //if (var some(x) = somemaybeint) { ... } } struct StructTest1 { var a : Int, c, b : Int typealias ElementType = Int } enum UnionTest1 { case x case y(Int) func foo() {} init() { self = .x } } extension UnionTest1 { func food() {} func bar() {} // Type method. static func baz() {} } struct EmptyStruct { func foo() {} } func f() { let a : UnionTest1 a.bar() UnionTest1.baz() // dot syntax access to a static method. // Test that we can get the "address of a member". var _ : () -> () = UnionTest1.baz var _ : (UnionTest1) -> () -> () = UnionTest1.bar } func union_error(_ a: ZeroOneTwoThree) { var _ : ZeroOneTwoThree = .Zero(1) // expected-error {{member 'Zero' takes no arguments}} var _ : ZeroOneTwoThree = .Zero() // expected-error {{member 'Zero' is not a function}} {{34-36=}} var _ : ZeroOneTwoThree = .One // expected-error {{member 'One' expects argument of type 'Int'}} var _ : ZeroOneTwoThree = .foo // expected-error {{type 'ZeroOneTwoThree' has no member 'foo'}} var _ : ZeroOneTwoThree = .foo() // expected-error {{type 'ZeroOneTwoThree' has no member 'foo'}} } func local_struct() { struct s { func y() {} } } //===----------------------------------------------------------------------===// // A silly units example showing "user defined literals". //===----------------------------------------------------------------------===// struct distance { var v : Int } func - (lhs: distance, rhs: distance) -> distance {} extension Int { func km() -> enumtest.distance {} func cm() -> enumtest.distance {} } func units(_ x: Int) -> distance { return x.km() - 4.cm() - 42.km() } var %% : distance -> distance // expected-error {{expected pattern}} func badTupleElement() { typealias X = (x : Int, y : Int) var y = X.y // expected-error{{type 'X' (aka '(x: Int, y: Int)') has no member 'y'}} var z = X.z // expected-error{{type 'X' (aka '(x: Int, y: Int)') has no member 'z'}} } enum Direction { case North(distance: Int) case NorthEast(distanceNorth: Int, distanceEast: Int) } func testDirection() { var dir: Direction = .North(distance: 5) dir = .NorthEast(distanceNorth: 5, distanceEast: 7) var i: Int switch dir { case .North(let x): i = x break case .NorthEast(let x): i = x.distanceEast break } _ = i } enum NestedSingleElementTuple { case Case(x: (y: Int)) // expected-error{{cannot create a single-element tuple with an element label}} {{17-20=}} } enum SimpleEnum { case X, Y } func testSimpleEnum() { let _ : SimpleEnum = .X let _ : SimpleEnum = (.X) let _ : SimpleEnum=.X // expected-error {{'=' must have consistent whitespace on both sides}} } enum SR510: String { case Thing = "thing" case Bob = {"test"} // expected-error {{raw value for enum case must be a literal}} } // <rdar://problem/21269142> Diagnostic should say why enum has no .rawValue member enum E21269142 { // expected-note {{did you mean to specify a raw type on the enum declaration?}} case Foo } print(E21269142.Foo.rawValue) // expected-error {{value of type 'E21269142' has no member 'rawValue'}} // Check that typo correction does something sensible with synthesized members. enum SyntheticMember { // expected-note {{did you mean the implicitly-synthesized property 'hashValue'?}} case Foo } print(SyntheticMember.Foo.hasValue) // expected-error {{value of type 'SyntheticMember' has no member 'hasValue'}} // Non-materializable argument type enum Lens<T> { case foo(inout T) // expected-error {{'inout' may only be used on parameters}} case bar(inout T, Int) // expected-error {{'inout' may only be used on parameters}} }
apache-2.0
PangeaSocialNetwork/PangeaGallery
PangeaMediaPicker/ImagePicker/BrowserCell.swift
1
868
// // BrowserCell.swift // PangeaMediaPicker // // Created by Roger Li on 2017/8/31. // Copyright © 2017年 Roger Li. All rights reserved. // import UIKit class BrowserCell: UICollectionViewCell { // Animation time let animationTime = 0.5 @IBOutlet var bigImage: UIImageView! var firstIndex:IndexPath = [] internal func setImageWithImage(_ image: UIImage, defaultImage: UIImage) { self.setBigImageTheSizeOfThe(image, defaultImage:defaultImage) } func setBigImageTheSizeOfThe(_ bImage: UIImage, defaultImage: UIImage) { self.bigImage.image = bImage } func indexPath() -> IndexPath? { if let collectionView = self.superview as? UICollectionView { let indexPath = collectionView.indexPath(for: self) return indexPath } else { return nil } } }
mit
ewhitley/CDAKit
CDAKit/health-data-standards/swift_helpers/String+CryptoExtensions.swift
1
1986
// // String+CryptoExtensions.swift // CDAKit // // Created by Eric Whitley on 12/17/15. // Copyright © 2015 Eric Whitley. All rights reserved. // //import Foundation //import CommonCrypto //http://stackoverflow.com/questions/25424831/cant-convert-nsdata-to-nsstring-in-swift //extension String { // func md5(string string: String) -> [UInt8] { // var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0) // if let data = string.dataUsingEncoding(NSUTF8StringEncoding) { // CC_MD5(data.bytes, CC_LONG(data.length), &digest) // } // // return digest // } // // func md5(string: String) -> NSData { // let digest = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH))! // if let data :NSData = string.dataUsingEncoding(NSUTF8StringEncoding) { // CC_MD5(data.bytes, CC_LONG(data.length), // UnsafeMutablePointer<UInt8>(digest.mutableBytes)) // } // return digest // } // // func md5Digest(string: NSString) -> NSString { // let data = string.dataUsingEncoding(NSUTF8StringEncoding)! // var hash = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0) // CC_MD5(data.bytes, CC_LONG(data.length), &hash) // let resstr = NSMutableString() // for byte in hash { // resstr.appendFormat("%02hhx", byte) // } // return resstr // } // func hnk_MD5String() -> String { // if let data = self.dataUsingEncoding(NSUTF8StringEncoding) // { // if let result = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH)) { // let resultBytes = UnsafeMutablePointer<CUnsignedChar>(result.mutableBytes) // CC_MD5(data.bytes, CC_LONG(data.length), resultBytes) // let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: result.length) // let MD5 = NSMutableString() // for c in resultEnumerator { // MD5.appendFormat("%02x", c) // } // return MD5 as String // } // } // return "" // } //}
mit
Eziohao/Caculator
Eziohao_Calculator/Eziohao_CalculatorTests/Eziohao_CalculatorTests.swift
1
940
// // Eziohao_CalculatorTests.swift // Eziohao_CalculatorTests // // Created by Eziohao's Mac on 15/7/18. // Copyright (c) 2015年 Eziohao's Mac. All rights reserved. // import UIKit import XCTest class Eziohao_CalculatorTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
wireapp/wire-ios
Wire-iOS/Sources/Helpers/syncengine/ZMUser+ExpirationTimeFormatting.swift
1
2538
//// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireDataModel fileprivate extension TimeInterval { var hours: Double { return self / 3600 } var minutes: Double { return self / 60 } } final class WirelessExpirationTimeFormatter { static let shared = WirelessExpirationTimeFormatter() private let numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.maximumFractionDigits = 1 return formatter }() func string(for user: UserType) -> String? { return string(for: user.expiresAfter) } func string(for interval: TimeInterval) -> String? { guard interval > 0 else { return nil } let (hoursLeft, minutesLeft) = (interval.hours, interval.minutes) guard hoursLeft < 2 else { return localizedHours(floor(hoursLeft) + 1) } if hoursLeft > 1 { let extraMinutes = minutesLeft - 60 return localizedHours(extraMinutes > 30 ? 2 : 1.5) } switch minutesLeft { case 45...Double.greatestFiniteMagnitude: return localizedHours(1) case 30..<45: return localizedMinutes(45) case 15..<30: return localizedMinutes(30) default: return localizedMinutes(15) } } private func localizedMinutes(_ minutes: Double) -> String { return "guest_room.expiration.less_than_minutes_left".localized(args: String(format: "%.0f", minutes)) } private func localizedHours(_ hours: Double) -> String { let localizedHoursString = numberFormatter.string(from: NSNumber(value: hours)) ?? "\(hours)" return "guest_room.expiration.hours_left".localized(args: localizedHoursString) } } extension UserType { var expirationDisplayString: String? { return WirelessExpirationTimeFormatter.shared.string(for: self) } }
gpl-3.0
benlangmuir/swift
validation-test/compiler_crashers_fixed/26017-swift-printingdiagnosticconsumer-handlediagnostic.swift
65
427
// 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 struct c{{}}if u{class case,
apache-2.0
benlangmuir/swift
test/IRGen/type_layout_dumper_all.swift
30
2621
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/type_layout_dumper_other.swiftmodule -module-name=type_layout_dumper_other %S/Inputs/type_layout_dumper_other.swift // RUN: %target-swift-frontend -dump-type-info -I %t %s | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: OS=macosx import type_layout_dumper_other // CHECK: --- // CHECK-NEXT: Name: type_layout_dumper_other // CHECK-NEXT: Decls: // CHECK-NEXT: - Name: 24type_layout_dumper_other21ConcreteFragileStructV // CHECK-NEXT: Size: 4 // CHECK-NEXT: Alignment: 4 // CHECK-NEXT: ExtraInhabitants: 0 // CHECK-NEXT: - Name: 24type_layout_dumper_other21ConcreteFragileStructV015NestedResilientG0V // CHECK-NEXT: Size: 0 // CHECK-NEXT: Alignment: 1 // CHECK-NEXT: ExtraInhabitants: 0 // CHECK-NEXT: - Name: 24type_layout_dumper_other21ConcreteResilientEnumO // CHECK-NEXT: Size: 9 // CHECK-NEXT: Alignment: 8 // CHECK-NEXT: ExtraInhabitants: 254 // CHECK-NEXT: - Name: 24type_layout_dumper_other22DependentResilientEnumO09NestedNonefG0O // CHECK-NEXT: Size: 8 // CHECK-NEXT: Alignment: 8 // CHECK-NEXT: ExtraInhabitants: 0 // CHECK-NEXT: - Name: 24type_layout_dumper_other23ConcreteResilientStructV // CHECK-NEXT: Size: 8 // CHECK-NEXT: Alignment: 8 // CHECK-NEXT: ExtraInhabitants: 0 // CHECK-NEXT: - Name: 24type_layout_dumper_other24DependentResilientStructV09NestedNonefG0V // CHECK-NEXT: Size: 8 // CHECK-NEXT: Alignment: 8 // CHECK-NEXT: ExtraInhabitants: 1 // CHECK-NEXT: - Name: 24type_layout_dumper_other25NonDependentFragileStructV // CHECK-NEXT: Size: 8 // CHECK-NEXT: Alignment: 8 // CHECK-NEXT: ExtraInhabitants: 2147483647 // CHECK-NEXT: - Name: 24type_layout_dumper_other25NonDependentResilientEnumO // CHECK-NEXT: Size: 8 // CHECK-NEXT: Alignment: 8 // CHECK-NEXT: ExtraInhabitants: 0 // CHECK-NEXT: - Name: 24type_layout_dumper_other27NonDependentResilientStructV // CHECK-NEXT: Size: 8 // CHECK-NEXT: Alignment: 8 // CHECK-NEXT: ExtraInhabitants: 2147483647 // CHECK-NEXT: - Name: Si24type_layout_dumper_otherE17NestedInExtensionV // CHECK-NEXT: Size: 4 // CHECK-NEXT: Alignment: 4 // CHECK-NEXT: ExtraInhabitants: 0 // CHECK-NEXT: ...
apache-2.0
benlangmuir/swift
test/Interop/SwiftToCxx/properties/setter-in-cxx.swift
2
8880
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend %s -typecheck -module-name Properties -clang-header-expose-public-decls -emit-clang-header-path %t/properties.h // RUN: %FileCheck %s < %t/properties.h // RUN: %check-interop-cxx-header-in-clang(%t/properties.h) public struct FirstSmallStruct { public var x: UInt32 } // CHECK: class FirstSmallStruct final { // CHECK: public: // CHECK: inline FirstSmallStruct(FirstSmallStruct &&) = default; // CHECK-NEXT: inline uint32_t getX() const; // CHECK-NEXT: inline void setX(uint32_t value); // CHECK-NEXT: private: public struct LargeStruct { public var x1, x2, x3, x4, x5, x6: Int } // CHECK: class LargeStruct final { // CHECK: public: // CHECK: inline LargeStruct(LargeStruct &&) = default; // CHECK-NEXT: inline swift::Int getX1() const; // CHECK-NEXT: inline void setX1(swift::Int value); // CHECK-NEXT: inline swift::Int getX2() const; // CHECK-NEXT: inline void setX2(swift::Int value); // CHECK-NEXT: inline swift::Int getX3() const; // CHECK-NEXT: inline void setX3(swift::Int value); // CHECK-NEXT: inline swift::Int getX4() const; // CHECK-NEXT: inline void setX4(swift::Int value); // CHECK-NEXT: inline swift::Int getX5() const; // CHECK-NEXT: inline void setX5(swift::Int value); // CHECK-NEXT: inline swift::Int getX6() const; // CHECK-NEXT: inline void setX6(swift::Int value); // CHECK-NEXT: private: public struct LargeStructWithProps { public var storedLargeStruct: LargeStruct public var storedSmallStruct: FirstSmallStruct } // CHECK: class LargeStructWithProps final { // CHECK-NEXT: public: // CHECK: inline LargeStruct getStoredLargeStruct() const; // CHECK-NEXT: inline void setStoredLargeStruct(const LargeStruct& value); // CHECK-NEXT: inline FirstSmallStruct getStoredSmallStruct() const; // CHECK-NEXT: inline void setStoredSmallStruct(const FirstSmallStruct& value); public final class PropertiesInClass { public var storedInt: Int32 init(_ x: Int32) { storedInt = x } public var computedInt: Int { get { return Int(storedInt) + 2 } set { storedInt = Int32(newValue - 2) } } } // CHECK: class PropertiesInClass final : public swift::_impl::RefCountedClass { // CHECK: using RefCountedClass::operator=; // CHECK-NEXT: inline int32_t getStoredInt(); // CHECK-NEXT: inline void setStoredInt(int32_t value); // CHECK-NEXT: inline swift::Int getComputedInt(); // CHECK-NEXT: inline void setComputedInt(swift::Int newValue); public func createPropsInClass(_ x: Int32) -> PropertiesInClass { return PropertiesInClass(x) } public struct SmallStructWithProps { public var storedInt: UInt32 public var computedInt: Int { get { return Int(storedInt) + 2 } set { storedInt = UInt32(newValue - 2) } } public var largeStructWithProps: LargeStructWithProps { get { return LargeStructWithProps(storedLargeStruct: LargeStruct(x1: computedInt * 2, x2: 1, x3: 2, x4: 3, x5: 4, x6: 5), storedSmallStruct:FirstSmallStruct(x: 0xFAE)) } set { print("SET: \(newValue.storedLargeStruct), \(newValue.storedSmallStruct)") } } } // CHECK: class SmallStructWithProps final { // CHECK: public: // CHECK: inline SmallStructWithProps(SmallStructWithProps &&) = default; // CHECK-NEXT: inline uint32_t getStoredInt() const; // CHECK-NEXT: inline void setStoredInt(uint32_t value); // CHECK-NEXT: inline swift::Int getComputedInt() const; // CHECK-NEXT: inline void setComputedInt(swift::Int newValue); // CHECK-NEXT: inline LargeStructWithProps getLargeStructWithProps() const; // CHECK-NEXT: inline void setLargeStructWithProps(const LargeStructWithProps& newValue); // CHECK-NEXT: private: public func createSmallStructWithProps() -> SmallStructWithProps { return SmallStructWithProps(storedInt: 21) } public func createFirstSmallStruct(_ x: UInt32) -> FirstSmallStruct { return FirstSmallStruct(x: x) } // CHECK: inline uint32_t FirstSmallStruct::getX() const { // CHECK-NEXT: return _impl::$s10Properties16FirstSmallStructV1xs6UInt32Vvg(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer())); // CHECK-NEXT: } // CHECK-NEXT: inline void FirstSmallStruct::setX(uint32_t value) { // CHECK-NEXT: return _impl::$s10Properties16FirstSmallStructV1xs6UInt32Vvs(value, _getOpaquePointer()); // CHECK-NEXT: } // CHECK: inline swift::Int LargeStruct::getX1() const { // CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x1Sivg(_getOpaquePointer()); // CHECK-NEXT: } // CHECK-NEXT: inline void LargeStruct::setX1(swift::Int value) { // CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x1Sivs(value, _getOpaquePointer()); // CHECK-NEXT: } // CHECK: inline LargeStruct LargeStructWithProps::getStoredLargeStruct() const { // CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) { // CHECK-NEXT: _impl::$s10Properties20LargeStructWithPropsV06storedbC0AA0bC0Vvg(result, _getOpaquePointer()); // CHECK-NEXT: }); // CHECK-NEXT: } // CHECK-NEXT: inline void LargeStructWithProps::setStoredLargeStruct(const LargeStruct& value) { // CHECK-NEXT: return _impl::$s10Properties20LargeStructWithPropsV06storedbC0AA0bC0Vvs(_impl::_impl_LargeStruct::getOpaquePointer(value), _getOpaquePointer()); // CHECK-NEXT: } // CHECK-NEXT: inline FirstSmallStruct LargeStructWithProps::getStoredSmallStruct() const { // CHECK-NEXT: return _impl::_impl_FirstSmallStruct::returnNewValue([&](char * _Nonnull result) { // CHECK-NEXT: _impl::swift_interop_returnDirect_Properties_uint32_t_0_4(result, _impl::$s10Properties20LargeStructWithPropsV011storedSmallC0AA05FirstgC0Vvg(_getOpaquePointer())); // CHECK-NEXT: }); // CHECK-NEXT: } // CHECK-NEXT: inline void LargeStructWithProps::setStoredSmallStruct(const FirstSmallStruct& value) { // CHECK-NEXT: return _impl::$s10Properties20LargeStructWithPropsV011storedSmallC0AA05FirstgC0Vvs(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_impl::_impl_FirstSmallStruct::getOpaquePointer(value)), _getOpaquePointer()); // CHECK-NEXT: } // CHECK: inline int32_t PropertiesInClass::getStoredInt() { // CHECK-NEXT: return _impl::$s10Properties0A7InClassC9storedInts5Int32Vvg(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this)); // CHECK-NEXT: } // CHECK-NEXT: inline void PropertiesInClass::setStoredInt(int32_t value) { // CHECK-NEXT: return _impl::$s10Properties0A7InClassC9storedInts5Int32Vvs(value, ::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this)); // CHECK-NEXT: } // CHECK-NEXT: inline swift::Int PropertiesInClass::getComputedInt() { // CHECK-NEXT: return _impl::$s10Properties0A7InClassC11computedIntSivg(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this)); // CHECK-NEXT: } // CHECK-NEXT: inline void PropertiesInClass::setComputedInt(swift::Int newValue) { // CHECK-NEXT: return _impl::$s10Properties0A7InClassC11computedIntSivs(newValue, ::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this)); // CHECK-NEXT: } // CHECK: inline uint32_t SmallStructWithProps::getStoredInt() const { // CHECK-NEXT: return _impl::$s10Properties20SmallStructWithPropsV9storedInts6UInt32Vvg(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer())); // CHECK-NEXT: } // CHECK-NEXT: inline void SmallStructWithProps::setStoredInt(uint32_t value) { // CHECK-NEXT: return _impl::$s10Properties20SmallStructWithPropsV9storedInts6UInt32Vvs(value, _getOpaquePointer()); // CHECK-NEXT: } // CHECK-NEXT: inline swift::Int SmallStructWithProps::getComputedInt() const { // CHECK-NEXT: return _impl::$s10Properties20SmallStructWithPropsV11computedIntSivg(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer())); // CHECK-NEXT: } // CHECK-NEXT: inline void SmallStructWithProps::setComputedInt(swift::Int newValue) { // CHECK-NEXT: return _impl::$s10Properties20SmallStructWithPropsV11computedIntSivs(newValue, _getOpaquePointer()); // CHECK-NEXT: } // CHECK-NEXT: inline LargeStructWithProps SmallStructWithProps::getLargeStructWithProps() const { // CHECK-NEXT: return _impl::_impl_LargeStructWithProps::returnNewValue([&](char * _Nonnull result) { // CHECK-NEXT: _impl::$s10Properties20SmallStructWithPropsV05largecdE0AA05LargecdE0Vvg(result, _impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer())); // CHECK-NEXT: }); // CHECK-NEXT: } // CHECK-NEXT: inline void SmallStructWithProps::setLargeStructWithProps(const LargeStructWithProps& newValue) { // CHECK-NEXT: return _impl::$s10Properties20SmallStructWithPropsV05largecdE0AA05LargecdE0Vvs(_impl::_impl_LargeStructWithProps::getOpaquePointer(newValue), _getOpaquePointer()); // CHECK-NEXT: }
apache-2.0
RichardAtDP/jbsignup
Sources/App/Models/lessons.swift
1
3529
// // lessons.swift // jbsignup // // Created by Richard on 2017-07-30. // import Foundation import Vapor import FluentProvider final class lesson: Model { var lessonId: String var familyId: String var dancerId: String let storage = Storage() init(lessonId:String, familyId:String, dancerId:String) throws { self.lessonId = lessonId self.familyId = familyId self.dancerId = dancerId } init(row: Row) throws { lessonId = try row.get("lessonId") familyId = try row.get("familyId") dancerId = try row.get("dancerId") } func makeRow() throws -> Row { var row = Row() try row.set("lessonId", lessonId) try row.set("familyId", familyId) try row.set("dancerId", dancerId) return row } } extension lesson: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { lesson in lesson.id() lesson.string("lessonId") lesson.string("familyId") lesson.string("dancerId") } } static func revert(_ database: Database) throws { try database.delete(self) } } extension lesson: JSONConvertible { convenience init(json: JSON) throws { try self.init( lessonId: json.get("lessonId"), familyId: json.get("familyId"), dancerId: json.get("dancerId") ) } func makeJSON() throws -> JSON { var json = JSON() try json.set("id", id) try json.set("lessonId", lessonId) try json.set("familyId", familyId) try json.set("dancerId", dancerId) return json } } extension lesson: Timestampable { } extension lesson: ResponseRepresentable { } func saveLesson(proData:Content, familyid:String) throws { // Swift freaks if it receives a string rather than an array, so make arrays. var lessonList = [Node]() var frequency = [Node]() var dancerId = [Node]() if proData["lesson"]!.array == nil { lessonList = [proData["lesson"]!.string!.makeNode(in: nil)] dancerId = [proData["dancer"]!.string!.makeNode(in: nil)] } else { lessonList = proData["lesson"]!.array! dancerId = proData["dancer"]!.array! } // Go through each item and save or update var i = 0 for chosenLesson in lessonList { let query = try lesson.makeQuery() try query.filter("lessonId",.equals,chosenLesson.string!) try query.filter("dancerId",.equals,dancerId[i].string!) try query.filter("familyId",.equals,familyid) if try query.count() == 0 { // New let Lesson = try lesson(lessonId:chosenLesson.string!, familyId:familyid, dancerId:dancerId[i].string!) try Lesson.save() } else { // Update existing let Lesson = try lesson.find(query.first()?.id) Lesson?.lessonId = chosenLesson.string! Lesson?.dancerId = dancerId[i].string! Lesson?.familyId = familyid try Lesson?.save() } i += 1 } }
mit
semiroot/SwiftyConstraints
Tests/SC208HelperTest.swift
1
1282
// // SC201Top.swift // SwiftyConstraints // // Created by Hansmartin Geiser on 15/04/17. // Copyright © 2017 Hansmartin Geiser. All rights reserved. // import XCTest @testable import SwiftyConstraints class SC208HelperTests: SCTest { func test00Update() { let superview = SCTestView() let subview1 = SCTestView() let subview2 = SCTestView() let subview3 = SCTestView() let swiftyConstraints = superview.swiftyConstraints() swiftyConstraints .attach(subview1) .attach(subview2) .attach(subview3) .updateConstraints() XCTAssertTrue(superview.layoutIfCalled, "Constraint update failed on superview") XCTAssertTrue(subview1.layoutIfCalled, "Constraint update failed on subview") XCTAssertTrue(subview2.layoutIfCalled, "Constraint update failed on subview") XCTAssertTrue(subview3.layoutIfCalled, "Constraint update failed on subview") } func test01execute() { let superview = SCView() let subview = SCView() let swiftyConstraints = superview.swiftyConstraints() swiftyConstraints .attach(subview) .execute({ (view) in XCTAssertEqual(subview, view, "Wrong view passed to execute closure") XCTAssertTrue(true, "?") }) } }
mit
xmkevinchen/CKMessagesKit
CKMessagesKit/Sources/Layout/CKMessagesViewLayoutAttributes.swift
1
3224
// // CKMessagesViewLayoutAttributes.swift // CKCollectionViewForDataCard // // Created by Kevin Chen on 8/24/16. // Copyright © 2016 Kevin Chen. All rights reserved. // import UIKit public class CKMessagesViewLayoutAttributes: UICollectionViewLayoutAttributes { public enum CKMessagesViewAvatarPosition { case left case right } public var avatarPosition: CKMessagesViewAvatarPosition public var incomingAvatarSize: CGSize public var outgoingAvatarSize: CGSize public var messageFont: UIFont public var messageBubbleContainerSize: CGSize public var messageSize: CGSize public var messageInsets: UIEdgeInsets public var topLabelHeight: CGFloat public var bubbleTopLabelHeight: CGFloat public var bottomLabelHeight: CGFloat public var isConfigured: Bool = false override init() { messageFont = UIFont.preferredFont(forTextStyle: .body) incomingAvatarSize = .zero outgoingAvatarSize = .zero messageInsets = .zero messageSize = .zero messageBubbleContainerSize = .zero topLabelHeight = 0.0 bubbleTopLabelHeight = 0.0 bottomLabelHeight = 0.0 avatarPosition = .left super.init() } override public func copy() -> Any { let copy = super.copy() as! CKMessagesViewLayoutAttributes copy.messageFont = messageFont copy.incomingAvatarSize = incomingAvatarSize copy.outgoingAvatarSize = outgoingAvatarSize copy.messageInsets = messageInsets copy.messageSize = messageSize copy.messageBubbleContainerSize = messageBubbleContainerSize copy.topLabelHeight = topLabelHeight copy.bubbleTopLabelHeight = bubbleTopLabelHeight copy.bottomLabelHeight = bottomLabelHeight copy.avatarPosition = avatarPosition copy.isConfigured = isConfigured return copy } override public func isEqual(_ object: Any?) -> Bool { if let attributes = object as? CKMessagesViewLayoutAttributes { if attributes.representedElementCategory == .cell { return messageFont == attributes.messageFont && incomingAvatarSize == attributes.incomingAvatarSize && outgoingAvatarSize == attributes.outgoingAvatarSize && messageInsets == attributes.messageInsets && messageSize == attributes.messageSize && messageBubbleContainerSize == attributes.messageBubbleContainerSize && topLabelHeight == attributes.topLabelHeight && bubbleTopLabelHeight == attributes.bubbleTopLabelHeight && bottomLabelHeight == attributes.bottomLabelHeight && avatarPosition == attributes.avatarPosition && isConfigured == attributes.isConfigured && super.isEqual(attributes) } else { return super.isEqual(attributes) } } return super.isEqual(object) } }
mit
inspace-io/Social-Service-Browser
Sources/SocialServiceBrowserConfigurator.swift
1
4527
// // SocialServiceBrowserConfigurator.swift // Social Service Browser // // Created by Michal Zaborowski on 27.09.2017. // Copyright © 2017 Inspace. All rights reserved. // import UIKit public enum SocialServiceBrowserSelectionMode { case select case download(maxSelectedItemsCount: Int) var maxSelectedItemsCount: Int { switch self { case .select: return 1 case .download(let count): return count } } } public enum SocialServiceBrowserDisplayMode { case list case grid } public protocol SocialServiceBrowserViewControllerUIConfigurable { var displayMode: SocialServiceBrowserDisplayMode { get } var backBarButtonItem: UIBarButtonItem { get } var closeBarButtonItem: UIBarButtonItem { get } var importBarButtonItem: UIBarButtonItem { get } func registerCells(for collectionView: UICollectionView) func reusableIdentifierForCell(`in` displayMode: SocialServiceBrowserDisplayMode) -> String func reusableIdentifierForHeader(`in` displayMode: SocialServiceBrowserDisplayMode) -> String } extension SocialServiceBrowserViewControllerUIConfigurable { public var backBarButtonItem: UIBarButtonItem { return UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil) } public var closeBarButtonItem: UIBarButtonItem { return UIBarButtonItem(title: "Close", style: .plain, target: nil, action: nil) } public var importBarButtonItem: UIBarButtonItem { return UIBarButtonItem(title: "Import", style: .plain, target: nil, action: nil) } } public protocol SocialServiceBrowserViewControllerConfigurable { var client: SocialServiceBrowserClient { get } var parentNode: SocialServiceBrowerNode? { get } var selectionMode: SocialServiceBrowserSelectionMode { get } func newConfiguration(with parentNode: SocialServiceBrowerNode) -> SocialServiceBrowserViewControllerConfigurable } public struct SocialServiceBrowserConfigurator: SocialServiceBrowserViewControllerConfigurable, SocialServiceBrowserViewControllerUIConfigurable { public let selectionMode: SocialServiceBrowserSelectionMode public let displayMode: SocialServiceBrowserDisplayMode = .grid public let client: SocialServiceBrowserClient public let parentNode: SocialServiceBrowerNode? public init(client: SocialServiceBrowserClient, parentNode: SocialServiceBrowerNode? = nil, selectionMode: SocialServiceBrowserSelectionMode = .select) { self.client = client self.parentNode = parentNode self.selectionMode = selectionMode } public func registerCells(for collectionView: UICollectionView) { collectionView.register(UINib(nibName: String(describing: SocialServiceBrowserGridCollectionViewCell.self), bundle: Bundle(for: SocialServiceBrowserGridCollectionViewCell.self)), forCellWithReuseIdentifier: reusableIdentifierForCell(in: .grid)) collectionView.register(UINib(nibName: String(describing: SocialServiceBrowserCollectionReusableView.self), bundle: Bundle(for: SocialServiceBrowserCollectionReusableView.self)), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: reusableIdentifierForHeader(in: .grid)) collectionView.register(UINib(nibName: String(describing: SocialServiceBrowserListCollectionViewCell.self), bundle: Bundle(for: SocialServiceBrowserListCollectionViewCell.self)), forCellWithReuseIdentifier: reusableIdentifierForCell(in: .list)) } public func reusableIdentifierForCell(in displayMode: SocialServiceBrowserDisplayMode) -> String { if displayMode == .list { return String(describing: SocialServiceBrowserListCollectionViewCell.self) } return String(describing: SocialServiceBrowserGridCollectionViewCell.self) } public func reusableIdentifierForHeader(in displayMode: SocialServiceBrowserDisplayMode) -> String { return String(describing: SocialServiceBrowserCollectionReusableView.self) } public func newConfiguration(with parentNode: SocialServiceBrowerNode) -> SocialServiceBrowserViewControllerConfigurable { return SocialServiceBrowserConfigurator(client: client, parentNode: parentNode) } }
apache-2.0
Pyroh/Fluor
Fluor/Views/LinkButton.swift
1
2793
// // LinkButton.swift // // Fluor // // MIT License // // Copyright (c) 2020 Pierre Tacchi // // 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 import SmoothOperators final class LinkButton: NSButton { @IBInspectable var url: String? private var actualURL: URL? { guard let url = url else { return nil } return URL(string: url) } override init(frame frameRect: NSRect) { super.init(frame: frameRect) setupAppearance() createAction() } required init?(coder: NSCoder) { super.init(coder: coder) setupAppearance() createAction() } private func setupAppearance() { isBordered = false imagePosition = .noImage alternateTitle = title var attributes = attributedTitle.fontAttributes(in: .init(location: 0, length: attributedTitle.length)) attributes[.foregroundColor] = NSColor.linkColor attributes[.underlineStyle] = NSUnderlineStyle.single.rawValue let newAttributedTitle = NSAttributedString(string: title, attributes: attributes) attributedTitle = newAttributedTitle attributedAlternateTitle = newAttributedTitle } private func createAction() { target = self action = #selector(openURL(_:)) } override func resetCursorRects() { super.resetCursorRects() self.addCursorRect(self.bounds, cursor: .pointingHand) } @IBAction func openURL(_ sender: Any?){ guard !!url else { return } guard let destinationURL = actualURL else { return assertionFailure("\(self.url!) is not a valid URL.") } NSWorkspace.shared.open(destinationURL) } }
mit
niceb5y/DRSTm
DRST manager/InfoViewController.swift
1
2263
// // InfoViewController.swift // DRST manager // // Created by 김승호 on 2016. 1. 30.. // Copyright © 2016년 Seungho Kim. All rights reserved. // import UIKit import SafariServices import DRSTKit class InfoViewController: UITableViewController { let dk = DataKit() @IBOutlet weak var accountSwitch: UISwitch! @IBOutlet weak var notificationSwitch: UISwitch! @IBOutlet weak var iCloudSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() accountSwitch.setOn(dk.dualAccountEnabled, animated: false) notificationSwitch.setOn(dk.notificationEnabled, animated: false) iCloudSwitch.setOn(dk.iCloudEnabled, animated: false) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if (indexPath as NSIndexPath).section == 1 { if (indexPath as NSIndexPath).row == 0 { let vc = SFSafariViewController(url: URL(string: "https://twitter.com/deresuteborder")!) self.present(vc, animated: true, completion: nil) } if (indexPath as NSIndexPath).row == 1 { let vc = SFSafariViewController(url: URL(string: "https://twitter.com/imas_ml_td_t")!) self.present(vc, animated: true, completion: nil) } } else if (indexPath as NSIndexPath).section == 2 { if (indexPath as NSIndexPath).row == 0 { let url = URL(string: "mailto:niceb5y+drstm@gmail.com?subject=%EB%8B%B9%EC%8B%A0%EC%9D%B4%20%EC%96%B4%EC%A7%B8%EC%84%9C%20%EA%B0%9C%EB%B0%9C%EC%9E%90%EC%9D%B8%EA%B1%B0%EC%A3%A0%3F") UIApplication.shared.openURL(url!) } } } @IBAction func accountSwitchTouched(_ sender: AnyObject) { dk.dualAccountEnabled = accountSwitch.isOn } @IBAction func notificationSwitchTouched(_ sender: AnyObject) { dk.notificationEnabled = notificationSwitch.isOn if notificationSwitch.isOn { let notificationSettings = UIUserNotificationSettings(types: UIUserNotificationType.sound.union(UIUserNotificationType.alert), categories: nil) UIApplication.shared.registerUserNotificationSettings(notificationSettings) UIApplication.shared.registerForRemoteNotifications() DRSTNotification.register() } else { DRSTNotification.clear() } } @IBAction func iCloudSwitchTouched(_ sender: AnyObject) { dk.iCloudEnabled = iCloudSwitch.isOn } }
mit
jjz/agora-swift
agora/MainViewController.swift
1
283
// // MainViewController.swift // agora // // Created by jjz on 09/04/2017. // Copyright © 2017 jjz. All rights reserved. // import Foundation import UIKit class MainViewController : UIViewController{ override func viewDidLoad() { super.viewDidLoad() } }
apache-2.0
mono0926/nlp100-swift
Carthage/Checkouts/SwiftyStringExtension/Tests/CharacterTests.swift
1
400
// // Tests.swift // Tests // // Created by mono on 2016/10/02. // Copyright © 2016 mono. All rights reserved. // import XCTest import SwiftyStringExtension class CharacterTests: XCTestCase { func testFromAsciiCode() { XCTAssertEqual(Character(asciiCode: 65), "A") XCTAssertEqual(Character(asciiCode: 97), "a") XCTAssertNil(Character(asciiCode: 1000)) } }
mit
stone-payments/onestap-sdk-ios
OnestapSDK/Core/Enums/OSTErrors.swift
1
427
// // OSTErrors.swift // OnestapSDK // // Created by Munir Wanis on 21/08/17. // Copyright © 2017 Stone Payments. All rights reserved. // import Foundation public enum OSTErrors: Error { case plistNotFound case configNotFound case incorrectIdentifier case malformedUri case stateIsInvalid case invalidOperation case failedToRetrieveSchemeFromPlist case wrongParameters(message: String) }
apache-2.0
michael-lehew/swift-corelibs-foundation
Foundation/NSObjCRuntime.swift
1
11239
// 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 // import CoreFoundation #if os(OSX) || os(iOS) internal let kCFCompareLessThan = CFComparisonResult.compareLessThan internal let kCFCompareEqualTo = CFComparisonResult.compareEqualTo internal let kCFCompareGreaterThan = CFComparisonResult.compareGreaterThan #endif internal enum _NSSimpleObjCType : UnicodeScalar { case ID = "@" case Class = "#" case Sel = ":" case Char = "c" case UChar = "C" case Short = "s" case UShort = "S" case Int = "i" case UInt = "I" case Long = "l" case ULong = "L" case LongLong = "q" case ULongLong = "Q" case Float = "f" case Double = "d" case Bitfield = "b" case Bool = "B" case Void = "v" case Undef = "?" case Ptr = "^" case CharPtr = "*" case Atom = "%" case ArrayBegin = "[" case ArrayEnd = "]" case UnionBegin = "(" case UnionEnd = ")" case StructBegin = "{" case StructEnd = "}" case Vector = "!" case Const = "r" } extension Int { init(_ v: _NSSimpleObjCType) { self.init(UInt8(ascii: v.rawValue)) } } extension Int8 { init(_ v: _NSSimpleObjCType) { self.init(Int(v)) } } extension String { init(_ v: _NSSimpleObjCType) { self.init(v.rawValue) } } extension _NSSimpleObjCType { init?(_ v: UInt8) { self.init(rawValue: UnicodeScalar(v)) } init?(_ v: String?) { if let rawValue = v?.unicodeScalars.first { self.init(rawValue: rawValue) } else { return nil } } } // mapping of ObjC types to sizes and alignments (note that .Int is 32-bit) // FIXME use a generic function, unfortuantely this seems to promote the size to 8 private let _NSObjCSizesAndAlignments : Dictionary<_NSSimpleObjCType, (Int, Int)> = [ .ID : ( MemoryLayout<AnyObject>.size, MemoryLayout<AnyObject>.alignment ), .Class : ( MemoryLayout<AnyClass>.size, MemoryLayout<AnyClass>.alignment ), .Char : ( MemoryLayout<CChar>.size, MemoryLayout<CChar>.alignment ), .UChar : ( MemoryLayout<UInt8>.size, MemoryLayout<UInt8>.alignment ), .Short : ( MemoryLayout<Int16>.size, MemoryLayout<Int16>.alignment ), .UShort : ( MemoryLayout<UInt16>.size, MemoryLayout<UInt16>.alignment ), .Int : ( MemoryLayout<Int32>.size, MemoryLayout<Int32>.alignment ), .UInt : ( MemoryLayout<UInt32>.size, MemoryLayout<UInt32>.alignment ), .Long : ( MemoryLayout<Int32>.size, MemoryLayout<Int32>.alignment ), .ULong : ( MemoryLayout<UInt32>.size, MemoryLayout<UInt32>.alignment ), .LongLong : ( MemoryLayout<Int64>.size, MemoryLayout<Int64>.alignment ), .ULongLong : ( MemoryLayout<UInt64>.size, MemoryLayout<UInt64>.alignment ), .Float : ( MemoryLayout<Float>.size, MemoryLayout<Float>.alignment ), .Double : ( MemoryLayout<Double>.size, MemoryLayout<Double>.alignment ), .Bool : ( MemoryLayout<Bool>.size, MemoryLayout<Bool>.alignment ), .CharPtr : ( MemoryLayout<UnsafePointer<CChar>>.size, MemoryLayout<UnsafePointer<CChar>>.alignment) ] internal func _NSGetSizeAndAlignment(_ type: _NSSimpleObjCType, _ size : inout Int, _ align : inout Int) -> Bool { guard let sizeAndAlignment = _NSObjCSizesAndAlignments[type] else { return false } size = sizeAndAlignment.0 align = sizeAndAlignment.1 return true } public func NSGetSizeAndAlignment(_ typePtr: UnsafePointer<Int8>, _ sizep: UnsafeMutablePointer<Int>?, _ alignp: UnsafeMutablePointer<Int>?) -> UnsafePointer<Int8> { let type = _NSSimpleObjCType(UInt8(typePtr.pointee))! var size : Int = 0 var align : Int = 0 if !_NSGetSizeAndAlignment(type, &size, &align) { // FIXME: This used to return nil, but the corresponding Darwin // implementation is defined as returning a non-optional value. fatalError("invalid type encoding") } sizep?.pointee = size alignp?.pointee = align return typePtr.advanced(by: 1) } public enum ComparisonResult : Int { case orderedAscending = -1 case orderedSame case orderedDescending internal static func _fromCF(_ val: CFComparisonResult) -> ComparisonResult { if val == kCFCompareLessThan { return .orderedAscending } else if val == kCFCompareGreaterThan { return .orderedDescending } else { return .orderedSame } } } /* Note: QualityOfService enum is available on all platforms, but it may not be implemented on all platforms. */ public enum NSQualityOfService : Int { /* UserInteractive QoS is used for work directly involved in providing an interactive UI such as processing events or drawing to the screen. */ case userInteractive /* UserInitiated QoS is used for performing work that has been explicitly requested by the user and for which results must be immediately presented in order to allow for further user interaction. For example, loading an email after a user has selected it in a message list. */ case userInitiated /* Utility QoS is used for performing work which the user is unlikely to be immediately waiting for the results. This work may have been requested by the user or initiated automatically, does not prevent the user from further interaction, often operates at user-visible timescales and may have its progress indicated to the user by a non-modal progress indicator. This work will run in an energy-efficient manner, in deference to higher QoS work when resources are constrained. For example, periodic content updates or bulk file operations such as media import. */ case utility /* Background QoS is used for work that is not user initiated or visible. In general, a user is unaware that this work is even happening and it will run in the most efficient manner while giving the most deference to higher QoS work. For example, pre-fetching content, search indexing, backups, and syncing of data with external systems. */ case background /* Default QoS indicates the absence of QoS information. Whenever possible QoS information will be inferred from other sources. If such inference is not possible, a QoS between UserInitiated and Utility will be used. */ case `default` } public struct NSSortOptions: OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let concurrent = NSSortOptions(rawValue: UInt(1 << 0)) public static let stable = NSSortOptions(rawValue: UInt(1 << 4)) } public struct NSEnumerationOptions: OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let concurrent = NSEnumerationOptions(rawValue: UInt(1 << 0)) public static let reverse = NSEnumerationOptions(rawValue: UInt(1 << 1)) } public typealias Comparator = (Any, Any) -> ComparisonResult public let NSNotFound: Int = Int.max internal func NSRequiresConcreteImplementation(_ fn: String = #function, file: StaticString = #file, line: UInt = #line) -> Never { fatalError("\(fn) must be overriden in subclass implementations", file: file, line: line) } internal func NSUnimplemented(_ fn: String = #function, file: StaticString = #file, line: UInt = #line) -> Never { #if os(Android) NSLog("\(fn) is not yet implemented. \(file):\(line)") #endif fatalError("\(fn) is not yet implemented", file: file, line: line) } internal func NSInvalidArgument(_ message: String, method: String = #function, file: StaticString = #file, line: UInt = #line) -> Never { fatalError("\(method): \(message)", file: file, line: line) } internal struct _CFInfo { // This must match _CFRuntimeBase var info: UInt32 var pad : UInt32 init(typeID: CFTypeID) { // This matches what _CFRuntimeCreateInstance does to initialize the info value info = UInt32((UInt32(typeID) << 8) | (UInt32(0x80))) pad = 0 } init(typeID: CFTypeID, extra: UInt32) { info = UInt32((UInt32(typeID) << 8) | (UInt32(0x80))) pad = extra } } #if os(OSX) || os(iOS) private let _SwiftFoundationModuleName = "SwiftFoundation" #else private let _SwiftFoundationModuleName = "Foundation" #endif /** Returns the class name for a class. For compatibility with Foundation on Darwin, Foundation classes are returned as unqualified names. Only top-level Swift classes (Foo.bar) are supported at present. There is no canonical encoding for other types yet, except for the mangled name, which is neither stable nor human-readable. */ public func NSStringFromClass(_ aClass: AnyClass) -> String { let aClassName = String(reflecting: aClass)._bridgeToObjectiveC() let components = aClassName.components(separatedBy: ".") guard components.count == 2 else { fatalError("NSStringFromClass: \(String(reflecting: aClass)) is not a top-level class") } if components[0] == _SwiftFoundationModuleName { return components[1] } else { return String(describing: aClassName) } } /** Returns the class metadata given a string. For compatibility with Foundation on Darwin, unqualified names are looked up in the Foundation module. Only top-level Swift classes (Foo.bar) are supported at present. There is no canonical encoding for other types yet, except for the mangled name, which is neither stable nor human-readable. */ public func NSClassFromString(_ aClassName: String) -> AnyClass? { let aClassNameWithPrefix : String let components = aClassName._bridgeToObjectiveC().components(separatedBy: ".") switch components.count { case 1: guard !aClassName.hasPrefix("_Tt") else { NSLog("*** NSClassFromString(\(aClassName)): cannot yet decode mangled class names") return nil } aClassNameWithPrefix = _SwiftFoundationModuleName + "." + aClassName break case 2: aClassNameWithPrefix = aClassName break default: NSLog("*** NSClassFromString(\(aClassName)): nested class names not yet supported") return nil } return _typeByName(aClassNameWithPrefix) as? AnyClass }
apache-2.0
Tulakshana/FileCache
FileCache/Example/FileCacheUITests/FileCacheUITests.swift
1
1262
// // FileCacheUITests.swift // FileCacheUITests // // Created by Weerasooriya, Tulakshana on 5/11/17. // Copyright © 2017 Tulakshana. All rights reserved. // import XCTest class FileCacheUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
Sensoro/FindBeaconWhenReActive-iOS
BeaconActiveSDKData-Swift/SensoroSDKActive-iOS/AppDelegate.swift
1
3067
// // AppDelegate.swift // SensoroSDKActive-iOS // // Created by David Yang on 15/4/8. // Copyright (c) 2015年 Sensoro. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. if((UIDevice.currentDevice().systemVersion as NSString).floatValue >= 8.0){ UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes:(.Alert | .Sound | .Badge), categories: nil)) UIApplication.sharedApplication().registerForRemoteNotifications() }else{ UIApplication.sharedApplication().registerForRemoteNotificationTypes((.Alert | .Sound | .Badge)) } //在通过Location唤醒时,launchOptions包含了UIApplicationLaunchOptionsLocationKey, //用于只是是从Location重新唤醒的。 if let options = launchOptions as! [NSString:AnyObject]?{ if let locationRestart = options[UIApplicationLaunchOptionsLocationKey] as? NSNumber { SENLocationManager.sharedInstance.startMonitor(true); } } 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:. } }
mit
jnollz/ShoesProxy
ShoesProxy/Setting.swift
1
386
// // Setting.swift // ShoesProxy // // Created by Jason on 4/28/16. // Copyright © 2016 Noll. All rights reserved. // import Foundation class Setting { // MARK: Properties var name: String var value: String init(name: String, value: String = "") { // Initialize stored properties self.name = name self.value = value } }
gpl-3.0
JasonPan/ADSSocialFeedScrollView
ADSSocialFeedScrollView/IntegratedSocialFeedScrollView/PostViewProtocol.swift
1
563
// // PostViewProtocol.swift // ADSSocialFeedScrollView // // Created by Jason Pan on 15/02/2016. // Copyright © 2016 ANT Development Studios. All rights reserved. // import Foundation /// An abstraction of a view that displays the contents of a post. protocol PostViewProtocol: class { /// The social platform provider for the post. var provider: ADSSocialFeedProvider { get } /// The content of the post. var postData: PostProtocol { get } /// Reloads the view to display updated post content. func refreshView() }
mit
natecook1000/swift
test/Constraints/iuo.swift
10
4765
// RUN: %target-typecheck-verify-swift func basic() { var i: Int! = 0 let _: Int = i i = 7 } func takesIUOs(i: Int!, j: inout Int!) -> Int { j = 7 return i } struct S { let i: Int! var j: Int! let k: Int var m: Int var n: Int! { get { return m } set { m = newValue } } var o: Int! { willSet { m = newValue } didSet { m = oldValue } } func fn() -> Int! { return i } static func static_fn() -> Int! { return 0 } subscript(i: Int) -> Int! { set { m = newValue } get { return i } } init(i: Int!, j: Int!, k: Int, m: Int) { self.i = i self.j = j self.k = k self.m = m } init!() { i = 0 j = 0 k = 0 m = 0 } } func takesStruct(s: S) { let _: Int = s.i let _: Int = s.j var t: S! = s t.j = 7 } var a: (Int, Int)! = (0, 0) a.0 = 42 var s: S! = S(i: nil, j: 1, k: 2, m: 3) _ = s.i let _: Int = s.j _ = s.k s.m = 7 s.j = 3 let _: Int = s[0] struct T { let i: Float! var j: Float! func fn() -> Float! { return i } } func overloaded() -> S { return S(i: 0, j: 1, k: 2, m: 3) } func overloaded() -> T { return T(i: 0.5, j: 1.5) } let _: Int = overloaded().i func cflow(i: Int!, j: inout Bool!, s: S) { let k: Int? = i let m: Int = i let b: Bool! = i == 0 if i == 7 { if s.i == 7 { } } let _ = b ? i : k let _ = b ? i : m let _ = b ? j : b let _ = b ? s.j : s.k if b {} if j {} let _ = j ? 7 : 0 } func forcedResultInt() -> Int! { return 0 } let _: Int = forcedResultInt() func forcedResult() -> Int! { return 0 } func forcedResult() -> Float! { return 0 } func overloadedForcedResult() -> Int { return forcedResult() } func forceMemberResult(s: S) -> Int { return s.fn() } func forceStaticMemberResult() -> Int { return S.static_fn() } func overloadedForceMemberResult() -> Int { return overloaded().fn() } func overloadedForcedStructResult() -> S! { return S(i: 0, j: 1, k: 2, m: 3) } func overloadedForcedStructResult() -> T! { return T(i: 0.5, j: 1.5) } let _: S = overloadedForcedStructResult() let _: Int = overloadedForcedStructResult().i func id<T>(_ t: T) -> T { return t } protocol P { } extension P { func iuoResult(_ b: Bool) -> Self! { } static func iuoResultStatic(_ b: Bool) -> Self! { } } func cast<T : P>(_ t: T) { let _: (T) -> (Bool) -> T? = id(T.iuoResult as (T) -> (Bool) -> T?) let _: (Bool) -> T? = id(T.iuoResult(t) as (Bool) -> T?) let _: T! = id(T.iuoResult(t)(true)) let _: (Bool) -> T? = id(t.iuoResult as (Bool) -> T?) let _: T! = id(t.iuoResult(true)) let _: T = id(t.iuoResult(true)) let _: (Bool) -> T? = id(T.iuoResultStatic as (Bool) -> T?) let _: T! = id(T.iuoResultStatic(true)) } class rdar37241550 { public init(blah: Float) { fatalError() } public convenience init() { fatalError() } public convenience init!(with void: ()) { fatalError() } static func f(_ fn: () -> rdar37241550) {} static func test() { f(rdar37241550.init) // no error, the failable init is not applicable } } class B {} class D : B { var i: Int! } func coerceToIUO(d: D?) -> B { return d as B! // expected-warning {{using '!' here is deprecated and will be removed in a future release}} } func forcedDowncastToOptional(b: B?) -> D? { return b as! D! // expected-warning {{using '!' here is deprecated and will be removed in a future release}} } func forcedDowncastToObject(b: B?) -> D { return b as! D! // expected-warning {{using '!' here is deprecated and will be removed in a future release}} } func forcedDowncastToObjectIUOMember(b: B?) -> Int { return (b as! D!).i // expected-warning {{using '!' here is deprecated and will be removed in a future release}} } func forcedUnwrapViaForcedCast(b: B?) -> B { return b as! B! // expected-warning {{forced cast from 'B?' to 'B' only unwraps optionals; did you mean to use '!'?}} // expected-warning@-1 {{using '!' here is deprecated and will be removed in a future release}} } func conditionalDowncastToOptional(b: B?) -> D? { return b as? D! // expected-warning {{using '!' here is deprecated and will be removed in a future release}} } func conditionalDowncastToObject(b: B?) -> D { return b as? D! // expected-error {{value of optional type 'D?' must be unwrapped}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} // expected-warning@-3 {{using '!' here is deprecated and will be removed in a future release}} } // Ensure that we select the overload that does *not* involve forcing an IUO. func sr6988(x: Int?, y: Int?) -> Int { return x! } func sr6988(x: Int, y: Int) -> Float { return Float(x) } var x: Int! = nil var y: Int = 2 let r = sr6988(x: x, y: y) let _: Int = r
apache-2.0
naveenrana1309/NRControls
NRControls/Classes/NRControls.swift
1
14341
// // NRControls.swift // // // Created by Naveen Rana on 21/08/16. // Developed by Naveen Rana. All rights reserved. // import Foundation import MessageUI fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } /// This completionhandler use for call back image picker controller delegates. public typealias ImagePickerControllerCompletionHandler = (_ controller: UIImagePickerController, _ info: [UIImagePickerController.InfoKey: Any]) -> Void /// This completionhandler use for call back mail controller delegates. public typealias MailComposerCompletionHandler = (_ result:MFMailComposeResult ,_ error: NSError?) -> Void /// This completionhandler use for call back alert(Alert) controller delegates. public typealias AlertControllerCompletionHandler = (_ alertController: UIAlertController, _ index: Int) -> Void /// This completionhandler use for call back alert(ActionSheet) controller delegates. public typealias AlertTextFieldControllerCompletionHandler = (_ alertController: UIAlertController, _ index: Int, _ text: String) -> Void /// This completionhandler use for call back of selected image using image picker controller delegates. public typealias CompletionImagePickerController = (_ selectedImage: UIImage?) -> Void /// This completionhandler use for call back of selected url using DocumentPicker controller delegates. public typealias DocumentPickerCompletionHandler = (_ selectedDocuments: [URL]?) -> Void /// This class is used for using a common controls like alert, action sheet and imagepicker controller with proper completion Handlers. open class NRControls: NSObject,UIImagePickerControllerDelegate,MFMailComposeViewControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate{ /// This completionhandler use for call back image picker controller delegates. var imagePickerControllerHandler: ImagePickerControllerCompletionHandler? /// This completionhandler use for call back mail controller delegates. var mailComposerCompletionHandler: MailComposerCompletionHandler? /// This completionhandler use for call back mail controller delegates. var documentPickerCompletionHandler: DocumentPickerCompletionHandler? ///Shared instance public static let sharedInstance = NRControls() /** This function is used for taking a picture from iphone camera or camera roll. - Parameters: - viewController: Source viewcontroller from which you want to present this popup. - completionHandler: This completion handler will give you image or nil. */ //MARK: UIImagePickerController open func takeOrChoosePhoto(_ viewController: UIViewController, completionHandler: @escaping CompletionImagePickerController) { let actionSheetController: UIAlertController = UIAlertController(title: "", message: "Choose photo", preferredStyle: .actionSheet) //Create and add the Cancel action let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in //Just dismiss the action sheet completionHandler(nil) } actionSheetController.addAction(cancelAction) //Create and add first option action //Create and add a second option action let takePictureAction: UIAlertAction = UIAlertAction(title: "Take Picture", style: .default) { action -> Void in self.openImagePickerController(.camera, isVideo: false, inViewController: viewController) { (controller, info) -> Void in let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage completionHandler(image) } } actionSheetController.addAction(takePictureAction) //Create and add a second option action let choosePictureAction: UIAlertAction = UIAlertAction(title: "Choose from library", style: .default) { action -> Void in self.openImagePickerController(.photoLibrary, isVideo: false, inViewController: viewController) { (controller, info) -> Void in let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage completionHandler(image) } } actionSheetController.addAction(choosePictureAction) if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad) { // In this case the device is an iPad. if let popoverController = actionSheetController.popoverPresentationController { popoverController.sourceView = viewController.view popoverController.sourceRect = viewController.view.bounds } } viewController.present(actionSheetController, animated: true, completion: nil) } /** This function is used open image picker controller. - Parameters: - sourceType: PhotoLibrary, Camera, SavedPhotosAlbum - inViewController: Source viewcontroller from which you want to present this imagecontroller. - isVideo: if you want to capture video then set it to yes, by default value is false. - completionHandler: Gives you the call back with Imagepickercontroller and information about image. */ open func openImagePickerController(_ sourceType: UIImagePickerController.SourceType, isVideo: Bool = false, inViewController:UIViewController, completionHandler: @escaping ImagePickerControllerCompletionHandler)-> Void { self.imagePickerControllerHandler = completionHandler let controller = UIImagePickerController() controller.allowsEditing = false controller.delegate = self; if UIImagePickerController.isSourceTypeAvailable(sourceType){ controller.sourceType = sourceType } else { print("this source type not supported in this device") } if (UI_USER_INTERFACE_IDIOM() == .pad) { //iPad support // In this case the device is an iPad. if let popoverController = controller.popoverPresentationController { popoverController.sourceView = inViewController.view popoverController.sourceRect = inViewController.view.bounds } } inViewController.present(controller, animated: true, completion: nil) } //MARK: UIImagePickerController Delegates public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { print("didFinishPickingMediaWithInfo") self.imagePickerControllerHandler!(picker, info) picker.dismiss(animated: true, completion: nil) } open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } /** This function is used for open Mail Composer. - Parameters: - recipientsEmailIds: email ids of recipents for you want to send emails. - viewcontroller: Source viewcontroller from which you want to present this mail composer. - subject: Subject of mail. - message: body of mail. - attachment: optional this is nsdata of video/photo or any other document. - completionHandler: Gives you the call back with result and error if any. */ //MARK: MFMailComposeViewController open func openMailComposerInViewController(_ recipientsEmailIds:[String], viewcontroller: UIViewController, subject: String = "", message: String = "" ,attachment: Data? = nil,completionHandler: @escaping MailComposerCompletionHandler){ if !MFMailComposeViewController.canSendMail() { print("No mail configured. please configure your mail first") return() } self.mailComposerCompletionHandler = completionHandler let mailComposerViewController = MFMailComposeViewController() mailComposerViewController.mailComposeDelegate = self mailComposerViewController.setSubject(subject) mailComposerViewController.setMessageBody(message, isHTML: true) mailComposerViewController.setToRecipients(recipientsEmailIds) if let _ = attachment { if (attachment!.count>0) { mailComposerViewController.addAttachmentData(attachment!, mimeType: "image/jpeg", fileName: "attachment.jpeg") } } viewcontroller.present(mailComposerViewController, animated: true, completion:nil) } //MARK: MFMailComposeViewController Delegates open func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion:nil) if self.mailComposerCompletionHandler != nil { self.mailComposerCompletionHandler!(result, error as NSError?) } } //MARK: AlertController /** This function is used for open Alert View. - Parameters: - viewcontroller: Source viewcontroller from which you want to present this mail composer. - title: title of the alert. - message: message of the alert . - buttonsTitlesArray: array of button titles eg: ["Cancel","Ok"]. - completionHandler: Gives you the call back with alertController and index of selected button . */ open func openAlertViewFromViewController(_ viewController: UIViewController, title: String = "", message: String = "", buttonsTitlesArray: [String], completionHandler: AlertControllerCompletionHandler?){ let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) for element in buttonsTitlesArray { let action:UIAlertAction = UIAlertAction(title: element, style: .default, handler: { (action) -> Void in if let _ = completionHandler { completionHandler!(alertController, buttonsTitlesArray.index(of: element)!) } }) alertController.addAction(action) } viewController.present(alertController, animated: true, completion: nil) } /** This function is used for open Action Sheet. - Parameters: - viewcontroller: Source viewcontroller from which you want to present this mail composer. - title: title of the alert. - message: message of the alert . - buttonsTitlesArray: array of button titles eg: ["Cancel","Ok"]. - completionHandler: Gives you the call back with alertController and index of selected button . */ open func openActionSheetFromViewController(_ viewController: UIViewController, title: String, message: String, buttonsTitlesArray: [String], completionHandler: AlertControllerCompletionHandler?){ let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) for element in buttonsTitlesArray { let action:UIAlertAction = UIAlertAction(title: element, style: .default, handler: { (action) -> Void in if let _ = completionHandler { completionHandler!(alertController, buttonsTitlesArray.index(of: element)!) } }) alertController.addAction(action) } viewController.present(alertController, animated: true, completion: nil) } /** This function is used for openAlertView with textfield. - Parameters: - viewcontroller: source viewcontroller from which you want to present this mail composer. - title: title of the alert. - message: message of the alert. - placeHolder: placeholder of the textfield. - isSecure: true if you want texfield secure, by default is false. - isNumberKeyboard: true if keyboard is of type numberpad, . - buttonsTitlesArray: array of button titles eg: ["Cancel","Ok"]. - completionHandler: Gives you the call back with alertController,index and text of textfield. */ open func openAlertViewWithTextFieldFromViewController(_ viewController: UIViewController, title: String = "", message: String = "", placeHolder: String = "", isSecure: Bool = false, buttonsTitlesArray: [String], isNumberKeyboard: Bool = false, completionHandler: AlertTextFieldControllerCompletionHandler?){ let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) for element in buttonsTitlesArray { let action: UIAlertAction = UIAlertAction(title: element, style: .default, handler: { (action) -> Void in if let _ = completionHandler { if let _ = alertController.textFields , alertController.textFields?.count > 0 , let text = alertController.textFields?.first?.text { completionHandler!(alertController, buttonsTitlesArray.index(of: element)!, text) } } }) alertController.addAction(action) } alertController.addTextField { (textField : UITextField!) -> Void in textField.isSecureTextEntry = isSecure textField.placeholder = placeHolder if isNumberKeyboard { textField.keyboardType = .numberPad } else { textField.keyboardType = .emailAddress } } viewController.present(alertController, animated: false, completion: nil) } }
mit
NqiOS/DYTV-swift
DYTV/DYTV/Classes/Home/View/NQCollectionGameCell.swift
1
768
// // NQCollectionGameCell.swift // DYTV // // Created by djk on 17/3/14. // Copyright © 2017年 NQ. All rights reserved. // import UIKit class NQCollectionGameCell: UICollectionViewCell { // MARK: 控件属性 @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var bottomLine: UIView! // MARK: 定义模型属性 var gameModel : NQBaseModel? { didSet { titleLabel.text = gameModel?.tag_name if let iconURL = URL(string: gameModel?.icon_url ?? "") { iconImageView.kf.setImage(with: iconURL) } else { iconImageView.image = UIImage(named: "home_more_btn") } } } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/14132-swift-sourcemanager-getmessage.swift
11
249
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing p( { protocol a { var d = [ { } { } var { enum e { { } func a( ) { class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/22532-swift-inflightdiagnostic.swift
11
275
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct S { init( ) { struct S { enum e { struct S struct S<T where g: A { let a { enum e { init( ) { p( )
mit
codefiesta/GitHubCodingChallenge
GitHub/Classes/Models/GitHubPullRequest.swift
1
717
// // GitHubPullRequest.swift // GitHub // // Created by Kevin McKee on 10/11/17. // Copyright © 2017 Procore. All rights reserved. // import Foundation // Represents a Pull Request public struct GitHubPullRequest: Codable { public var number: Int public var title: String public var state: String public var createDate: Date public var url: String public var diffUrl: String public var filesUrl: String { get { return "\(url)/files" } } enum CodingKeys: String, CodingKey { case number case title case state case createDate = "created_at" case url case diffUrl = "diff_url" } }
mit
OlliePoole/SimplePageViewController
SimplePageViewController.swift
1
3259
import Foundation import UIKit protocol SimplePageViewControllerDelegate { func simplePageViewController(pageViewController: SimplePageViewController, didMoveToPage page: UIViewController) } class SimplePageViewController : UIPageViewController { var customViewControllers : Array<UIViewController> /// Allows the page vew controlller to manage a page control var pageControl : UIPageControl? var pageDelegate: SimplePageViewControllerDelegate? /** Initalises a new UIPageViewController and sets the view controllers passsed as a parameter to the datasource - parameter viewControllers: The view controllers included in the UIPageViewController */ init(withViewControllers viewControllers : Array<UIViewController>) { // Initalise the properties self.customViewControllers = viewControllers // Call the super designated initaliser super.init(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil) // Set the UIPageViewController view controllers and default settings setViewControllers([customViewControllers[0]], direction: .Forward, animated: true, completion: nil) dataSource = self delegate = self } required init?(coder aDecoder: NSCoder) { self.customViewControllers = Array<UIViewController>() super.init(coder: aDecoder) } func moveToViewController(atIndex index: Int, direction: UIPageViewControllerNavigationDirection) { assert(index < customViewControllers.count, "Index out of bounds") let newViewController = customViewControllers[index] setViewControllers([newViewController], direction: direction, animated: true, completion: nil) } } extension SimplePageViewController : UIPageViewControllerDataSource { func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { var nextViewController: UIViewController? if let index = customViewControllers.indexOf(viewController) { pageControl?.currentPage = index if index != customViewControllers.count - 1 { nextViewController = customViewControllers[index + 1] } } return nextViewController } func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { var nextViewController: UIViewController? if let index = customViewControllers.indexOf(viewController) { pageControl?.currentPage = index if index != 0 { nextViewController = customViewControllers[index - 1] } } return nextViewController } } extension SimplePageViewController : UIPageViewControllerDelegate { func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if let viewController = pageViewController.viewControllers?.first { pageDelegate?.simplePageViewController(self, didMoveToPage: viewController) } } }
apache-2.0
mightydeveloper/swift
validation-test/compiler_crashers_fixed/25645-llvm-bitstreamcursor-read.swift
13
282
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol C{ let:C let h:e typealias e:d {}typealias e{ } class d:e
apache-2.0
nakiostudio/EasyPeasy
EasyPeasy/DimensionAttribute+UIKit.swift
1
3576
// The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal // // 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. #if os(iOS) || os(tvOS) import UIKit /** DimensionAttribute extension adding some convenience methods to operate with UIKit elements as `UIViews` or `UILayoutGuides` */ public extension DimensionAttribute { /** Establishes a relationship between the dimension attribute applied to the `UIView` and the reference `UIView` passed as parameter. It's also possible to link this relationship to a particular attribute of the `view` parameter by supplying `attribute`. - parameter view: The reference view - parameter attribute: The attribute of `view` we are establishing the relationship to - returns: The current `Attribute` instance */ @discardableResult func like(_ view: UIView, _ attribute: ReferenceAttribute? = nil) -> Self { self.referenceItem = view self.referenceAttribute = attribute return self } /** Establishes a relationship between the dimension attribute applied to the `UIView` and the reference `UILayoutGuide` passed as parameter. It's also possible to link this relationship to a particular attribute of the `layoutGuide` parameter by supplying `attribute`. - parameter layoutGuide: The reference `UILayoutGuide` - parameter attribute: The attribute of `layoutGuide` we are establishing the relationship to - returns: The current `Attribute` instance */ @available (iOS 9.0, *) @discardableResult func like(_ layoutGuide: UILayoutGuide, _ attribute: ReferenceAttribute? = nil) -> Self { self.referenceItem = layoutGuide self.referenceAttribute = attribute return self } } /** Size extension adding some convenience methods to let this CompoundAttribute operate with UIKit elements like `UIViews` or `UILayoutGuides` */ public extension Size { /** Establishes a relationship between the dimension attribute applied to the `UIView` and the reference `UIView` passed as parameter. - parameter view: The reference view - returns: The current `CompoundAttribute` instance */ @discardableResult func like(_ view: UIView) -> Self { self.referenceItem = view for attr in self.attributes { attr.referenceItem = view } return self } /** Establishes a relationship between the dimension attribute applied to the `UIView` and the reference `UILayoutGuide` passed as parameter. - parameter layoutGuide: The reference `UILayoutGuide` - returns: The current `CompoundAttribute` instance */ @available (iOS 9.0, *) @discardableResult func like(_ layoutGuide: UILayoutGuide) -> Self { self.referenceItem = layoutGuide for attr in self.attributes { attr.referenceItem = layoutGuide } return self } } #endif
mit