repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
atuooo/notGIF
notGIF/Views/GIFList/GIFListActionView.swift
1
5830
// // LongPressPopShareView.swift // notGIF // // Created by ooatuoo on 2017/6/16. // Copyright © 2017年 xyz. All rights reserved. // import UIKit class GIFListActionView: UIView { fileprivate var iconViews: [UIView] = [] fileprivate var iconTriggerRects: [CGRect] = [] fileprivate var actionTypes: [GIFActionType] = [] fileprivate var hasChanged: Bool = false fileprivate var cellMaskRect: CGRect = .zero fileprivate var isForIntro: Bool = false init(popOrigin: CGPoint, cellRect: CGRect, frame: CGRect = UIScreen.main.bounds, isForIntro: Bool = false) { super.init(frame: frame) backgroundColor = UIColor.black.withAlphaComponent(0.7) alpha = 0 self.isForIntro = isForIntro cellMaskRect = cellRect if isForIntro { actionTypes = GIFActionType.defaultActions } else { actionTypes = NGUserDefaults.customActions if !OpenShare.canOpen(.wechat) { actionTypes.remove(.shareTo(.wechat)) } } let iconS: CGFloat = 36 let padding: CGFloat = 16 let spaceV: CGFloat = 12 let count = actionTypes.count let totalW = CGFloat(count) * iconS + CGFloat(count - 1) * padding var beignOx: CGFloat if totalW/2 + popOrigin.x > (kScreenWidth - padding/2) { beignOx = kScreenWidth - totalW - padding / 2 } else if popOrigin.x - totalW/2 < padding / 2 { beignOx = padding/2 } else { beignOx = popOrigin.x - totalW/2 } let baseOriginY: CGFloat = cellRect.minY - spaceV - iconS for i in 0..<count { let iconViewFrame = CGRect(x: beignOx, y: baseOriginY, width: iconS, height: iconS) let iconView = UIImageView(image: actionTypes[i].icon) iconView.contentMode = .scaleAspectFit iconView.tintColor = UIColor.textTint iconView.frame = iconViewFrame.insetBy(dx: 3, dy: 3) beignOx += iconS + padding iconView.alpha = 0 let iconTriggerRect = CGRect(x: iconViewFrame.minX - padding/2, y: baseOriginY, width: iconS+padding, height: cellRect.maxY - iconViewFrame.minY) iconTriggerRects.append(iconTriggerRect) iconViews.append(iconView) addSubview(iconView) } restore() } override func didMoveToWindow() { super.didMoveToWindow() if !isForIntro { animate() } } public func animate() { let duration = isForIntro ? 1.2 : 0.6 UIView.animate(withDuration: 0.3) { self.alpha = 1 } UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: [.curveEaseIn], animations: { self.iconViews.forEach { $0.alpha = 1 ; $0.transform = .identity } }, completion: nil) } public func restore() { alpha = 0 for i in 0..<iconViews.count { let iconView = iconViews[i] iconView.alpha = 0 if i % 2 == 0 { let transformT = CGAffineTransform(translationX: 0, y: iconView.frame.width) let transformR = CGAffineTransform(rotationAngle: CGFloat.pi * 0.3) let transfromS = CGAffineTransform(scaleX: 0.2, y: 0.2) iconView.transform = transformT.concatenating(transfromS).concatenating(transformR) } else { let transformT = CGAffineTransform(translationX: 0, y: -iconView.frame.width) let transformR = CGAffineTransform(rotationAngle: CGFloat.pi * 0.7) let transfromS = CGAffineTransform(scaleX: 0.3, y: 0.3) iconView.transform = transformT.concatenating(transfromS).concatenating(transformR) } } } override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() context?.setFillColor(UIColor.clear.cgColor) context?.setBlendMode(.clear) context?.fillEllipse(in: cellMaskRect.insetBy(dx: 4, dy: 2)) } public func update(with offset: CGPoint) { hasChanged = true let transfromS = CGAffineTransform(scaleX: 1.2, y: 1.2) let transformT = CGAffineTransform(translationX: 0, y: -12) let transform = transformT.concatenating(transfromS) let index = iconTriggerRects.index(where: { $0.contains(offset) }) UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: [.curveEaseInOut], animations: { for i in 0..<self.iconViews.count { if index == i { self.iconViews[i].transform = transform } else { self.iconViews[i].transform = .identity } } }, completion: nil) } public func end(with offset: CGPoint) -> GIFActionType? { UIView.animate(withDuration: 0.2, animations: { self.alpha = 0 }) { _ in self.removeFromSuperview() } guard hasChanged else { return nil } if let index = iconTriggerRects.index(where: { $0.contains(offset) }) { return actionTypes[index] } else { return nil } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
9dff02532715b08e68afd7d4f1076b62
32.877907
157
0.557748
4.620936
false
false
false
false
nguyenantinhbk77/practice-swift
Tutorials/Developing_iOS_Apps_With_Swift/lesson8/lesson8/DetailsViewController.swift
3
2828
import UIKit import MediaPlayer import QuartzCore class DetailsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, APIControllerProtocol{ @lazy var api: APIController = APIController(delegate: self) var album: Album? @IBOutlet var albumTitle : UILabel @IBOutlet var cover : UIImageView @IBOutlet var tracksTableView: UITableView var tracks: Track[] = [] var mediaPlayer = MPMoviePlayerController() init(coder aDecoder: NSCoder!){ super.init(coder: aDecoder) } override func viewDidLoad(){ super.viewDidLoad() //self.albumTitle.text = album?.title //var url = NSURL(string:self.album?.largeImageURL) //var data = NSData(contentsOfURL:url) //self.cover.image = UIImage(data: data) if self.album?.collectionId?{ self.api.lookupAlbum(self.album!.collectionId!) } } func didReceiveAPIResults(results: NSDictionary) { if let allResults = results["results"] as? NSDictionary[] { for trackInfo in allResults { // Create the track if let kind = trackInfo["kind"] as? String { if kind=="song" { var track = Track(dict: trackInfo) tracks.append(track) } } } } dispatch_async(dispatch_get_main_queue(), { self.tracksTableView.reloadData() }) } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return tracks.count } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { var cell = tableView.dequeueReusableCellWithIdentifier("TrackCell") as TrackCell var track = tracks[indexPath.row] cell.titleLabel.text = track.title println(track.title) cell.playIcon.text = "▶️" return cell } func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) { cell.layer.transform = CATransform3DMakeScale(0.1,0.1,1) UIView.animateWithDuration(0.25, animations: { cell.layer.transform = CATransform3DMakeScale(1,1,1) }) } func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { var track = tracks[indexPath.row] mediaPlayer.stop() mediaPlayer.contentURL = NSURL(string: track.previewUrl) mediaPlayer.play() if let cell = tableView.cellForRowAtIndexPath(indexPath) as? TrackCell { cell.playIcon.text = "▪️" } } }
mit
8c80ced61068b79ebb3aa58417649610
31.425287
128
0.608156
5.164835
false
false
false
false
mrlegowatch/JSON-to-Swift-Converter
JSON to Swift ConverterUITests/JSONtoSwiftConverterUITests.swift
1
4771
// // JSONtoSwiftConverterUITests.swift // JSON to Swift Converter // // Created by Brian Arnold on 2/20/17. // Copyright © 2018 Brian Arnold. All rights reserved. // import XCTest class JSONtoSwiftConverterUITests: XCTestCase { override func setUp() { super.setUp() continueAfterFailure = false XCUIApplication().launch() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSettings() { let window = XCUIApplication().windows["JSON to Swift Converter Settings"] let letRadioButton = window.radioButtons["let"] let varRadioButton = window.radioButtons["var"] let explicitRadioButton = window.radioButtons["Explicit"] let optionalRadioButton = window.radioButtons["? Optional"] let requiredRadioButton = window.radioButtons["! Required"] let supportCodableCheckBox = window.checkBoxes["Support Codable"] let addDefaultValuesCheckBox = window.checkBoxes["Add default values"] let outputStaticText = window.staticTexts["outputStaticText"] // TODO: "reset" the target application's UserDefaults default suite settings in // a way that actually works. The trick used in the logic unit tests doesn't work // here. Is it because we are out-of-process, don't have entitlements for the suite, // or something else? In the meantime, we instead reset the initial state of the controls. // Reset the initial state of the controls letRadioButton.click() requiredRadioButton.click() if let value = supportCodableCheckBox.value as? Int, value != 1 { supportCodableCheckBox.click() } if let value = addDefaultValuesCheckBox.value as? Int, value != 0 { addDefaultValuesCheckBox.click() } // Validate the initial state of the controls XCTAssertEqual(letRadioButton.value as? Int, 1, "let should be selected") XCTAssertEqual(varRadioButton.value as? Int, 0, "var should not be selected") XCTAssertEqual(explicitRadioButton.value as? Int, 0, "explicit should not be selected") XCTAssertEqual(optionalRadioButton.value as? Int, 0, "optional should not be selected") XCTAssertEqual(requiredRadioButton.value as? Int, 1, "required should be selected") XCTAssertEqual(supportCodableCheckBox.value as? Int, 1, "add key should be selected") XCTAssertEqual(addDefaultValuesCheckBox.value as? Int, 0, "add default values should be deselected") // Confirm the initial state of the output static text do { let output = outputStaticText.value as? String let lines = output?.components(separatedBy: "\n") XCTAssertEqual(lines?.count, 10, "number of lines of output") } varRadioButton.click() XCTAssertEqual(letRadioButton.value as? Int, 0, "let should not be selected") XCTAssertEqual(varRadioButton.value as? Int, 1, "var should be selected") optionalRadioButton.click() XCTAssertEqual(explicitRadioButton.value as? Int, 0, "explicit should not be selected") XCTAssertEqual(optionalRadioButton.value as? Int, 1, "optional should be selected") XCTAssertEqual(requiredRadioButton.value as? Int, 0, "required should not be selected") explicitRadioButton.click() XCTAssertEqual(explicitRadioButton.value as? Int, 1, "explicit should be selected") XCTAssertEqual(optionalRadioButton.value as? Int, 0, "optional should not be selected") XCTAssertEqual(requiredRadioButton.value as? Int, 0, "required should not be selected") supportCodableCheckBox.click() XCTAssertEqual(supportCodableCheckBox.value as? Int, 0, "add key should not be selected") do { let output = outputStaticText.value as? String let lines = output?.components(separatedBy: "\n") XCTAssertEqual(lines?.count, 9, "number of lines of output") } addDefaultValuesCheckBox.click() XCTAssertEqual(addDefaultValuesCheckBox.value as? Int, 1, "add default values should be selected") // Turn add key back on so we can test add init and add var dictionary supportCodableCheckBox.click() do { let output = outputStaticText.value as? String let lines = output?.components(separatedBy: "\n") XCTAssertEqual(lines?.count, 10, "number of lines of output") } } }
mit
9445caa2a85ff3b39125b21f34447c5d
43.166667
111
0.657023
4.973931
false
true
false
false
webelectric/AspirinKit
AspirinKit/Sources/Foundation/String+Extensions.swift
1
11701
// // String.swift // AspirinKit // // Copyright © 2014 - 2017 The Web Electric Corp. // // 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 let spaceCharacterSet = CharacterSet.whitespaces public extension String { var length:Int { return self.characters.count } var NSStr:NSString { return (self as NSString) } var float:Float? { return Float(self) } var double:Double? { return Double(self) } var int:Int? { return Int(self) } var fourCharCode:FourCharCode { assert(self.characters.count == 4, "String length must be 4") var result : FourCharCode = 0 for char in self.utf16 { result = (result << 8) + FourCharCode(char) } return result } static func createUUID() -> String { return UUID().uuidString } public init(base64Value: String) { let data = Data(base64Encoded: base64Value, options: Data.Base64DecodingOptions(rawValue: 0)) self = String(data: data!, encoding: String.Encoding.utf8)! } var base64Value: String { let data = self.data(using: String.Encoding.utf8) return data!.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) } public func trim() -> String { return self.trimmingCharacters(in: CharacterSet.whitespaces) } ///a String qualifies as 'blank' if it's either nil or only made up of spaces public static func isBlank(_ val:String!) -> Bool { if val == nil { return true } return val.trim().isEmpty } mutating public func removed(prefix: String) { let prefixStartIndex = self.index(self.startIndex, offsetBy: prefix.characters.count) let range = self.startIndex..<prefixStartIndex self.removeSubrange(range) } public func removing(prefix: String) -> String { if !self.hasPrefix(prefix) { return self } let prefixStartIndex = self.characters.index(self.startIndex, offsetBy: prefix.characters.count) return String(self[prefixStartIndex...]) } public func removing(suffix: String) -> String { let position = self.position(of: suffix) if position == -1 { return self } let toIdx = self.index(self.startIndex, offsetBy: position) return String(self[..<toIdx]) } public func substring(from startIndex: Int, length: Int) -> String { let start = self.characters.index(self.startIndex, offsetBy: startIndex) let end = self.characters.index(self.startIndex, offsetBy: startIndex + length) return String(self[start ..< end]) } public func position(of substring: String) -> Int { if let range = self.range(of: substring) { return self.characters.distance(from: self.startIndex, to: range.lowerBound) } else { return -1 } } public func position(of substring: String, from startIndex: Int) -> Int { let startRange = self.characters.index(self.startIndex, offsetBy: startIndex) let range = self.range(of: substring, options: NSString.CompareOptions.literal, range: Range<String.Index>(startRange ..< self.endIndex)) if let rangeResult = range { return self.characters.distance(from: self.startIndex, to: rangeResult.lowerBound) } else { return -1 } } public func lastPosition(of substring: String) -> Int { var index = -1 var stepIndex = self.position(of: substring) while stepIndex > -1 { index = stepIndex if (stepIndex + substring.length) < self.length { stepIndex = self.position(of: substring, from: (stepIndex + substring.length)) } else { stepIndex = -1 } } return index } public subscript(i: Int) -> Character { get { let index = characters.index(startIndex, offsetBy: i) return self[index] } } public subscript(i: Int) -> String { return String(self[i] as Character) } fileprivate var vowels: [String] { return ["a", "e", "i", "o", "u"] } fileprivate var consonants: [String] { return ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "z"] } public func pluralized(by count: Int, with locale: Locale = Locale(identifier: "en_US")) -> String { let localeLanguage = locale.languageCode ?? "en" if localeLanguage != "en" { print("Error plularizing, only languageCode = 'en' is supported at this time, returning unmodified string.") return self } if count == 1 { return self } else { let len = self.length let lastChar = self.substring(from: len - 1, length: 1) let secondToLastChar = self.substring(from: len - 2, length: 1) var prefix = "", suffix = "" if lastChar.lowercased() == "y" && vowels.filter({x in x == secondToLastChar}).count == 0 { let toIdx = self.index(self.startIndex, offsetBy: (len - 1)) prefix = String(self[..<toIdx])// self[0..<(self.length - 1)] suffix = "ies" } else if lastChar.lowercased() == "s" || (lastChar.lowercased() == "o" && consonants.filter({x in x == secondToLastChar}).count > 0) { let toIdx = self.index(self.startIndex, offsetBy: (len)) prefix = String(self[..<toIdx])// self[0..<(self.length - 1)] // prefix = self[0..<self.length] suffix = "es" } else { let toIdx = self.index(self.startIndex, offsetBy: (len)) prefix = String(self[..<toIdx])// self[0..<(self.length - 1)] // prefix = self[0..<self.length] suffix = "s" } return prefix + (lastChar != lastChar.uppercased() ? suffix : suffix.uppercased()) } } } public extension String { ///removes prefix if present mutating public func removePrefix(_ prefix: String) { let prefixStartIndex = self.index(self.startIndex, offsetBy: prefix.characters.count) let range = self.startIndex..<prefixStartIndex self.removeSubrange(range) } public func stringByRemovingPrefix(_ prefix: String) -> String { if !self.hasPrefix(prefix) { return self } let prefixStartIndex = self.characters.index(self.startIndex, offsetBy: prefix.characters.count) return String(self[prefixStartIndex...]) } public func stringByRemovingSuffix(_ suffix: String) -> String { let position = self.indexOf(suffix) if position == -1 { return self } let toIdx = self.index(self.startIndex, offsetBy: position) return String(self[..<toIdx]) } public func subString(_ startIndex: Int, length: Int) -> String { let start = self.characters.index(self.startIndex, offsetBy: startIndex) let end = self.characters.index(self.startIndex, offsetBy: startIndex + length) return String(self[start ..< end]) } public func indexOf(_ substring: String) -> Int { if let range = self.range(of: substring) { return self.characters.distance(from: self.startIndex, to: range.lowerBound) } else { return -1 } } public func indexOf(_ substring: String, startIndex: Int) -> Int { let startRange = self.characters.index(self.startIndex, offsetBy: startIndex) let range = self.range(of: substring, options: NSString.CompareOptions.literal, range: Range<String.Index>(startRange ..< self.endIndex)) if let rangeResult = range { return self.characters.distance(from: self.startIndex, to: rangeResult.lowerBound) } else { return -1 } } public func lastIndexOf(_ substring: String) -> Int { var index = -1 var stepIndex = self.indexOf(substring) while stepIndex > -1 { index = stepIndex if (stepIndex + substring.length) < self.length { stepIndex = self.indexOf(substring, startIndex: (stepIndex + substring.length)) } else { stepIndex = -1 } } return index } // public func contains(_ substring:String) -> Bool { // return self.indexOf(substring) != -1 // } public func pluralize(_ count: Int) -> String { if count == 1 { return self } else { let lastChar = self.subString(self.length - 1, length: 1) let secondToLastChar = self.subString(self.length - 2, length: 1) var prefix = "", suffix = "" if lastChar.lowercased() == "y" && vowels.filter({x in x == secondToLastChar}).count == 0 { print(prefix) let toIdx = self.index(self.startIndex, offsetBy: (self.length - 1)) prefix = String(self[..<toIdx])// self[0..<(self.length - 1)] print(prefix) suffix = "ies" } else if lastChar.lowercased() == "s" || (lastChar.lowercased() == "o" && consonants.filter({x in x == secondToLastChar}).count > 0) { let toIdx = self.index(self.startIndex, offsetBy: (self.length)) prefix = String(self[..<toIdx])// self[0..<(self.length - 1)] // prefix = self[0..<self.length] suffix = "es" } else { let toIdx = self.index(self.startIndex, offsetBy: (self.length)) prefix = String(self[..<toIdx])// self[0..<(self.length - 1)] // prefix = self[0..<self.length] suffix = "s" } return prefix + (lastChar != lastChar.uppercased() ? suffix : suffix.uppercased()) } }}
mit
215e420678868e3c67f6e45ea41ca6f6
33.718101
145
0.560171
4.455446
false
false
false
false
zSher/BulletThief
BulletThief/BulletThief/LinePathBulletEffect.swift
1
1624
// // LinePathBulletEffect.swift // BulletThief // // Created by Zachary on 5/4/15. // Copyright (c) 2015 Zachary. All rights reserved. // import Foundation import SpriteKit /// This bullet effect... /// /// * Sets the path of the bullet to be a stright line up or down class LinePathBulletEffect: NSObject, NSCoding, BulletEffectProtocol { var path: UIBezierPath! override init() { var linePath = UIBezierPath() linePath.moveToPoint(CGPointZero) //MoveOnPath action is relative to object using it, start 0,0 linePath.addLineToPoint(CGPointMake(0, 550)) self.path = linePath } // directional initializer. init(direction: Directions) { if direction == Directions.Down { var linePath = UIBezierPath() linePath.moveToPoint(CGPointZero) //MoveOnPath action is relative to object using it, start 0,0 linePath.addLineToPoint(CGPointMake(0, -650)) self.path = linePath } else { var linePath = UIBezierPath() linePath.moveToPoint(CGPointZero) //MoveOnPath action is relative to object using it, start 0,0 linePath.addLineToPoint(CGPointMake(0, 550)) self.path = linePath } } required init(coder aDecoder: NSCoder) { self.path = aDecoder.decodeObjectForKey("path") as UIBezierPath } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(path, forKey: "path") } func applyEffect(gun: Gun) { for bullet in gun.bulletPool { bullet.path = self.path } } }
mit
f5996ef1e71432fff761b11d9e843f55
29.074074
107
0.633005
4.511111
false
false
false
false
DianQK/rx-sample-code
PDFExpertContents/ContentItemModel.swift
1
1527
// // ContentItemModel.swift // PDF-Expert-Contents // // Created by DianQK on 24/09/2016. // Copyright © 2016 DianQK. All rights reserved. // import Foundation import RxDataSources import SwiftyJSON import RxExtensions typealias ExpandableContentItemModel = ExpandableItem<ContentItemModel> struct ContentItemModel: IDHashable, IdentifiableType { let id: Int64 let title: String let level: Int let url: URL? init(title: String, level: Int, id: Int64, url: URL?) { self.title = title self.level = level self.id = id self.url = url } var hashValue: Int { return id.hashValue } var identity: Int64 { return id } static func createExpandableContentItemModel(json: JSON, withPreLevel preLevel: Int) -> ExpandableContentItemModel { let title = json["title"].stringValue let id = json["id"].int64Value let url = URL(string: json["url"].stringValue) let level = preLevel + 1 let subItems: [ExpandableContentItemModel] if let subJSON = json["subdirectory"].array, !subJSON.isEmpty { subItems = subJSON.map { createExpandableContentItemModel(json: $0, withPreLevel: level) } } else { subItems = [] } let contentItemModel = ContentItemModel(title: title, level: level, id: id, url: url) let expandableItem = ExpandableItem(model: contentItemModel, isExpanded: false, subItems: subItems) return expandableItem } }
mit
e5bebd6e0784eabfe6485573a1d3ccef
26.25
120
0.653342
4.238889
false
false
false
false
MakeSchool/Swift-Playgrounds
More-P1-Properties.playground/Contents.swift
2
3910
import UIKit /*: Let's talk properties! Properties associate values with the class/structure they belong to. There are 2 types of properties: stored properties and computed properties. Stored properties store values for the instance of the class/structure. On the other hand, computed properties have no actual values, but their values are computed on the spot when they are accessed. We will discuss the 2 types of properties in more detail. */ /*: Let's start with stored properties! A class/structure can have both variable or constant stored properties. Each stored property can have a default value, and if the property is a variable, its value can change in the future. Let's look at some examples: */ class SomeClass { let a: Int var b: String init(a: Int, b: String) { self.a = a self.b = b } } /*: It is important to understand that properties cannot be left without a value unless they are optionals (where their default value is nil). Try uncommenting the init function and see what kind of error you get. The compiler gives an error because when an object of SomeClass is created, the values of a and b will not be be set to anything. For that reason, you need an initializer that will set their values or you have to give default values to the properties. */ /*: Let's look at a code that uses this class: */ var item = SomeClass(a: 10, b: "Swift rocks!") /*: In order to access the properties of the object, you use dot notation: */ println(item.b) /*: Let's now take a look at computed properties. In the class below, num is a stored property becuse it actually stores an integer, but take a look at str property. It does not store any values. It only creates a string whenever it is accessed. Make sure you understand the syntax: for a computed property, you do not say "= 50" for example. You instead, open a block "{ }" and inside there, you add "get { }", and in that block you will return a value for the computed property. */ class SomeClass2 { var num: Int = 50 var str: String { get { return "Swift rocks \(num) times!" } } } /*: Notice, there are no custom initializers. That is becuase num has a default value, and computed properties do not need to be initialized. As a result, the class is already initialized and ready to go. There is no need to add an init function. */ var item2 = SomeClass2() /*: What is happening when you write "item2.str"? Since str is a computed property, the program calls its get block, and uses the returned value as the property's value. */ println(item2.str) /*: Notice how we change only the num property, but the value of str also changes based on that. That is because str's value is computed when it is accessed, based on the value of num. */ item2.num = 100 println(item2.str) /*: Now let's look at what more you can do with properties. It is possible to observe when a property's value changes, so as a class, you can act accordingly. As you can see below, there are 2 blocks you can add to each property, willSet and didSet. willSet is called just before the new value is stored and didSet is called right after the new value is set. In willSet, self.num still contains the old value. In order to access the new value, you use newValue variable. In didSet, self.num contains the new value. In order to access the old value, you use oldValue variable. */ class SomeClass3 { var num: Int = 50 { willSet { if newValue > self.num { } } didSet { if self.num == oldValue { self.num * 2 } } } var str: String { get { return "Swift rocks \(num) times!" } } } /*: Notice that during initialization, the willSet/diSet blocks are not called. */ let item3 = SomeClass3() item3.num = 60
mit
6a5f89d73b4157c20051375f3f8ef995
35.886792
476
0.697442
4.217907
false
false
false
false
chaosarts/ChaosMath.swift
ChaosMath/basis2.swift
1
6222
// // basis2.swift // ChaosMath // // Created by Fu Lam Diep on 09/10/2016. // Copyright © 2016 Fu Lam Diep. All rights reserved. // import Foundation public struct tbasis2<T: ArithmeticScalarType>: Equatable { /* +-------------------------------------------------------------------------- | Typealiases +-------------------------------------------------------------------------- */ /// Describes the data type of the components public typealias ElementType = T /// Describes its own type public typealias SelfType = tbasis2<ElementType> /// Decribes the VectorType public typealias VectorType = tvec2<ElementType> /// Decribes the MatrixType public typealias MatrixType = tmat2<ElementType> /* +-------------------------------------------------------------------------- | Stored properties +-------------------------------------------------------------------------- */ /// Provides the first vector of the basis public let b1: VectorType /// Provides the second vector of the basis public let b2: VectorType /* +-------------------------------------------------------------------------- | Derived properties +-------------------------------------------------------------------------- */ /// Provides the first basis vector public var x: VectorType { return b1 } /// Provides the first basis vector public var y: VectorType { return b2 } /// Represents the basis as matrix public var mat: MatrixType { return MatrixType(b1, b2) } /* +-------------------------------------------------------------------------- | Initialisers +-------------------------------------------------------------------------- */ /// Initializes the basis with the standard basis vectors public init () { b1 = VectorType.e1 b2 = VectorType.e2 } /// Initializes the basis with given basis vectors /// - parameter b1: The first basis vector /// - parameter b2: The second basis vector public init?<ForeignType: ArithmeticScalarType> (_ b1: tvec2<ForeignType>, _ b2: tvec2<ForeignType>) { if determinant(b1, b2) == 0 { return nil } self.b1 = VectorType(b1) self.b2 = VectorType(b2) } /// Initializes the basis with a matrix /// - parameter mat: The matrix to adopt the public init?<ForeignType: ArithmeticScalarType> (_ mat: tmat2<ForeignType>) { let determinant : ForeignType = mat.det if determinant == 0 { return nil } b1 = VectorType(mat.array[0], mat.array[1]) b2 = VectorType(mat.array[2], mat.array[3]) } /// Copies a basis public init<ForeignType: ArithmeticScalarType> (_ basis: tbasis2<ForeignType>) { b1 = VectorType(basis.b1) b2 = VectorType(basis.b2) } } public typealias basis2i = tbasis2<Int> public typealias basis2f = tbasis2<Float> public typealias basis2d = tbasis2<Double> public typealias basis2 = basis2f /* +------------------------------------------------------------------------------ | Operators +------------------------------------------------------------------------------ */ public func ==<ElementType: ArithmeticScalarType> (left: tbasis2<ElementType>, right: tbasis2<ElementType>) -> Bool { return left.b1 == right.b1 && left.b2 == right.b2 } /* +------------------------------------------------------------------------------ | Functions +------------------------------------------------------------------------------ */ /// Returns the transformation matrix from one basis to another /// - parameter from: The basis to transform from /// - parameter to: The basis to transform to /// - returns: The transformation matrix public func transformation<T: ArithmeticIntType> (fromBasis from: tbasis2<T>, toBasis to: tbasis2<T>) -> mat2f { let invertedMat : mat2f = try! invert(to.mat) return invertedMat * mat2f(from.mat) } /// Returns the transformation matrix from one basis to another /// - parameter from: The basis to transform from /// - parameter to: The basis to transform to /// - returns: The transformation matrix public func transformation<T: ArithmeticFloatType> (fromBasis from: tbasis2<T>, toBasis to: tbasis2<T>) -> tmat2<T> { let inverseTo : tmat2<T> = try! invert(to.mat) return inverseTo * from.mat } /// Returns the orthognal version of given basis /// - parameter basis: The basis to orthogonalize /// - parameter normalize: Indicates, whether to normalize the basis or not public func gramschmidt<T: ArithmeticScalarType> (_ basis: tbasis2<T>, _ normalize: Bool = false) -> tbasis2<Float>? { return gramschmidt(basis.b1, basis.b2) } /// Returns a orthogonal basis out of the given two vectors, if not collinear /// - parameter w1: The first vector /// - parameter w2: The second vector /// - parameter normalize: Indicates, whether to normalize the basis or not public func gramschmidt<T: ArithmeticScalarType> (_ w1: tvec2<T>, _ w2: tvec2<T>, _ normalize: Bool = false) -> tbasis2<Float>? { if determinant(w1, w2) == 0 { return nil } var v1 : tvec2<Float> = tvec2<Float>(w1) var v2 : tvec2<Float> = tvec2<Float>(w2) v2 -= dot(v1, v2) / dot(v1, v1) * v1 if normalize { v1 = ChaosMath.normalize(v1) v2 = ChaosMath.normalize(v2) } return tbasis2<Float>(v1, v2) } /// Returns a orthogonal basis out of the given two vectors, if not collinear /// - parameter w1: The first vector /// - parameter w2: The second vector /// - parameter normalize: Indicates, whether to normalize the basis or not public func gramschmidt (_ w1: vec2d, _ w2: vec2d, _ normalize: Bool = false) -> basis2d? { if determinant(w1, w2) == 0 { return nil } var v1 : vec2d = w1 var v2 : vec2d = w2 - dot(v1, w2) / dot(v1, v1) * v1 if normalize { v1 = ChaosMath.normalize(v1) v2 = ChaosMath.normalize(v2) } return basis2d(v1, v2) }
gpl-3.0
ede7bab987a742b912cfda4b6ec243b8
28.76555
129
0.533516
4.37175
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/00363-swift-scopeinfo-addtoscope.swift
1
924
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func j<f: l: e -> e = { { l) { m } } protocol k { class func j() } class e: k{ class func j } class i { func d((h: (Any, AnyObject)) { } } func d<i>() -> (i, i -> i) -> i { i j i.f = { } protocol d { } class i: d{ class func f {} enum A : String { } struct d<f : e, g: e where g.h == f.h> { } } extension d) { } func a() { c a(b: Int = 0) { } func m<u>() -> (u, u -> u) -> u { p o p.s = { } { o.m == o> (m: o) { } st.C == E> {s func c() { } } } st> { } func prefix(with: Strin-> <r>(() -> r) -> h { n { u o "\(v): \(u()" }
apache-2.0
6ef3843d77e4a59d44a1d34a9a1451e7
17.117647
79
0.566017
2.52459
false
false
false
false
ben-ng/swift
stdlib/public/core/StringIndexConversions.swift
1
7823
//===----------------------------------------------------------------------===// // // 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension String.Index { /// Creates an index in the given string that corresponds exactly to the /// specified `UnicodeScalarView` position. /// /// The following example converts the position of the Unicode scalar `"e"` /// into its corresponding position in the string's character view. The /// character at that position is the composed `"é"` character. /// /// let cafe = "Cafe\u{0301}" /// print(cafe) /// // Prints "Café" /// /// let scalarsIndex = cafe.unicodeScalars.index(of: "e")! /// let charactersIndex = String.Index(scalarsIndex, within: cafe)! /// /// print(String(cafe.characters.prefix(through: charactersIndex))) /// // Prints "Café" /// /// If the position passed in `unicodeScalarIndex` doesn't have an exact /// corresponding position in `other.characters`, the result of the /// initializer is `nil`. For example, an attempt to convert the position of /// the combining acute accent (`"\u{0301}"`) fails. Combining Unicode /// scalars do not have their own position in a character view. /// /// let nextIndex = String.Index(cafe.unicodeScalars.index(after: scalarsIndex), /// within: cafe) /// print(nextIndex) /// // Prints "nil" /// /// - Parameters: /// - unicodeScalarIndex: A position in the `unicodeScalars` view of the /// `other` parameter. /// - other: The string referenced by both `unicodeScalarIndex` and the /// resulting index. public init?( _ unicodeScalarIndex: String.UnicodeScalarIndex, within other: String ) { if !other.unicodeScalars._isOnGraphemeClusterBoundary(unicodeScalarIndex) { return nil } self.init(_base: unicodeScalarIndex, in: other.characters) } /// Creates an index in the given string that corresponds exactly to the /// specified `UTF16View` position. /// /// The following example finds the position of a space in a string's `utf16` /// view and then converts that position to an index in the string's /// `characters` view. The value `32` is the UTF-16 encoded value of a space /// character. /// /// let cafe = "Café 🍵" /// /// let utf16Index = cafe.utf16.index(of: 32)! /// let charactersIndex = String.Index(utf16Index, within: cafe)! /// /// print(String(cafe.characters.prefix(upTo: charactersIndex))) /// // Prints "Café" /// /// If the position passed in `utf16Index` doesn't have an exact /// corresponding position in `other.characters`, the result of the /// initializer is `nil`. For example, an attempt to convert the position of /// the trailing surrogate of a UTF-16 surrogate pair fails. /// /// The next example attempts to convert the indices of the two UTF-16 code /// points that represent the teacup emoji (`"🍵"`). The index of the lead /// surrogate is successfully converted to a position in `other.characters`, /// but the index of the trailing surrogate is not. /// /// let emojiHigh = cafe.utf16.index(after: utf16Index) /// print(String.Index(emojiHigh, within: cafe)) /// // Prints "Optional(String.Index(...))" /// /// let emojiLow = cafe.utf16.index(after: emojiHigh) /// print(String.Index(emojiLow, within: cafe)) /// // Prints "nil" /// /// - Parameters: /// - utf16Index: A position in the `utf16` view of the `other` parameter. /// - other: The string referenced by both `utf16Index` and the resulting /// index. public init?( _ utf16Index: String.UTF16Index, within other: String ) { if let me = utf16Index.samePosition( in: other.unicodeScalars )?.samePosition(in: other) { self = me } else { return nil } } /// Creates an index in the given string that corresponds exactly to the /// specified `UTF8View` position. /// /// If the position passed in `utf8Index` doesn't have an exact corresponding /// position in `other.characters`, the result of the initializer is `nil`. /// For example, an attempt to convert the position of a UTF-8 continuation /// byte returns `nil`. /// /// - Parameters: /// - utf8Index: A position in the `utf8` view of the `other` parameter. /// - other: The string referenced by both `utf8Index` and the resulting /// index. public init?( _ utf8Index: String.UTF8Index, within other: String ) { if let me = utf8Index.samePosition( in: other.unicodeScalars )?.samePosition(in: other) { self = me } else { return nil } } /// Returns the position in the given UTF-8 view that corresponds exactly to /// this index. /// /// The index must be a valid index of `String(utf8).characters`. /// /// This example first finds the position of the character `"é"` and then uses /// this method find the same position in the string's `utf8` view. /// /// let cafe = "Café" /// if let i = cafe.characters.index(of: "é") { /// let j = i.samePosition(in: cafe.utf8) /// print(Array(cafe.utf8.suffix(from: j))) /// } /// // Prints "[195, 169]" /// /// - Parameter utf8: The view to use for the index conversion. /// - Returns: The position in `utf8` that corresponds exactly to this index. public func samePosition( in utf8: String.UTF8View ) -> String.UTF8View.Index { return String.UTF8View.Index(self, within: utf8) } /// Returns the position in the given UTF-16 view that corresponds exactly to /// this index. /// /// The index must be a valid index of `String(utf16).characters`. /// /// This example first finds the position of the character `"é"` and then uses /// this method find the same position in the string's `utf16` view. /// /// let cafe = "Café" /// if let i = cafe.characters.index(of: "é") { /// let j = i.samePosition(in: cafe.utf16) /// print(cafe.utf16[j]) /// } /// // Prints "233" /// /// - Parameter utf16: The view to use for the index conversion. /// - Returns: The position in `utf16` that corresponds exactly to this index. public func samePosition( in utf16: String.UTF16View ) -> String.UTF16View.Index { return String.UTF16View.Index(self, within: utf16) } /// Returns the position in the given view of Unicode scalars that /// corresponds exactly to this index. /// /// The index must be a valid index of `String(unicodeScalars).characters`. /// /// This example first finds the position of the character `"é"` and then uses /// this method find the same position in the string's `unicodeScalars` /// view. /// /// let cafe = "Café" /// if let i = cafe.characters.index(of: "é") { /// let j = i.samePosition(in: cafe.unicodeScalars) /// print(cafe.unicodeScalars[j]) /// } /// // Prints "é" /// /// - Parameter unicodeScalars: The view to use for the index conversion. /// - Returns: The position in `unicodeScalars` that corresponds exactly to /// this index. public func samePosition( in unicodeScalars: String.UnicodeScalarView ) -> String.UnicodeScalarView.Index { return String.UnicodeScalarView.Index(self, within: unicodeScalars) } }
apache-2.0
84ded3f10da50343b8f36632daa25a90
36.873786
86
0.6283
4.078411
false
false
false
false
GongChengKuangShi/DYZB
DouYuTV/DouYuTV/Classes/Home/ViewController/RecommentdViewController.swift
1
6163
// // RecommentdViewController.swift // DouYuTV // // Created by xrh on 2017/9/6. // Copyright © 2017年 xiangronghua. All rights reserved. // //抓取数据(抓包):http://study.163.com/course/courseLearn.htm?courseId=1003309014&from=study#/learn/video?lessonId=1004015396&courseId=1003309014 //课件地址: http://study.163.com/course/courseLearn.htm?courseId=1003309014&from=study#/learn/video?lessonId=1004020290&courseId=1003309014 import UIKit private let kItemMargin : CGFloat = 10 private let kItemW = (kScreenW - 3 * kItemMargin) / 2 private let kNormalItemH = kItemW * 3 / 4 private let kPrortyItemH = kItemW * 4 / 3 private let kHeaderViewH : CGFloat = 50 private let kGameViewH : CGFloat = 90 private let kCycleViewH = kScreenW * 3 / 8 private let kNormalCellID = "kNormalCellID" private let kHeaderViewID = "kHeaderViewID" private let kPrortyCellID = "kPrortyCellID" class RecommentdViewController: UIViewController { // -- 懒加载 lazy var recommendVM : RecommendViewModel = RecommendViewModel() lazy var collectionView : UICollectionView = { [unowned self] in //1、创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) //2、创建UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView.register(UINib(nibName: "CollectionNormalViewCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.register(UINib(nibName: "CollectionPrortyViewCell", bundle: nil), forCellWithReuseIdentifier: kPrortyCellID) collectionView.register(UINib(nibName:"CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) return collectionView }() lazy var cycleView : RecommandCycleView = { let cycleView = RecommandCycleView.recommandCycleView() cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH) return cycleView }() lazy var gameView : RecommandGameView = { let gameView = RecommandGameView.recommandGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) return gameView }() override func viewDidLoad() { super.viewDidLoad() //设置UI界面 setupUI() //数据请求 loadData() } } //MARK:-- 设置UI界面内容 extension RecommentdViewController { func setupUI() { view.addSubview(collectionView) //添加cycleView collectionView.addSubview(cycleView) //添加gameView进入collectionView collectionView.addSubview(gameView) //设置collectView的内边距 collectionView.contentInset = UIEdgeInsetsMake(kCycleViewH + kGameViewH, 0, 0, 0) } } //MARK: 遵守UIcollectionView的代理协议 extension RecommentdViewController : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return recommendVM.anchorGroup.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let group = recommendVM.anchorGroup[section] return group.anchers.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //取出模型 let group = recommendVM.anchorGroup[indexPath.section] let ancher = group.anchers[indexPath.item] var cell : CollectionBaseCell! if indexPath.section == 1 { cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrortyCellID, for: indexPath) as! CollectionPrortyViewCell } else { cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID , for: indexPath) as! CollectionNormalViewCell } cell.anchor = ancher return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { //1、取出section的HeaderView let headView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView //2、取出模型 headView.group = recommendVM.anchorGroup[indexPath.section] return headView } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kItemW, height: kPrortyItemH) } return CGSize(width: kItemW, height: kNormalItemH) } } //--发送网络请求 extension RecommentdViewController { func loadData() { //请求推荐数据 recommendVM.requestData { self.collectionView.reloadData() //将数据传到gameView self.gameView.groups = self.recommendVM.anchorGroup } //请求轮播数据 recommendVM.requestCycleData { self.cycleView.cycleModel = self.recommendVM.cycleModel } } }
mit
66f201cbd8d9b4d7e5987c85cdbc5348
33.148571
185
0.678715
5.246708
false
false
false
false
sydvicious/firefox-ios
Client/Frontend/Browser/SessionData.swift
2
1060
/* 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 SessionData: NSObject, NSCoding { let currentPage: Int let urls: [NSURL] let lastUsedTime: Timestamp init(currentPage: Int, urls: [NSURL], lastUsedTime: Timestamp) { self.currentPage = currentPage self.urls = urls self.lastUsedTime = lastUsedTime } required init(coder: NSCoder) { self.currentPage = coder.decodeObjectForKey("currentPage") as? Int ?? 0 self.urls = coder.decodeObjectForKey("urls") as? [NSURL] ?? [] self.lastUsedTime = UInt64(coder.decodeInt64ForKey("lastUsedTime")) ?? NSDate.now() } func encodeWithCoder(coder: NSCoder) { coder.encodeObject(currentPage, forKey: "currentPage") coder.encodeObject(urls, forKey: "urls") coder.encodeInt64(Int64(lastUsedTime), forKey: "lastUsedTime") } }
mpl-2.0
59e8f5cbd038f7888ac342306682bf88
33.225806
91
0.675472
4.140625
false
false
false
false
RobinFalko/Ubergang
Ubergang/Core/Engine.swift
1
2075
// // Engine.swift // Ubergang // // Created by Robin Frielingsdorf on 09/01/16. // Copyright © 2016 Robin Falko. All rights reserved. // import Foundation import UIKit open class Engine: NSObject { public typealias Closure = () -> Void fileprivate var displayLink: CADisplayLink? var closures = [String : Closure]() var mapTable = NSMapTable<AnyObject, AnyObject>(keyOptions: NSPointerFunctions.Options.strongMemory, valueOptions: NSPointerFunctions.Options.weakMemory) public static var instance: Engine = { let engine = Engine() engine.start() return engine }() func start() { if displayLink == nil { displayLink = CADisplayLink(target: self, selector: #selector(Engine.update)) displayLink!.add(to: .current, forMode: .common) } } func stop() { displayLink?.remove(from: .current, forMode: .common) displayLink = nil } @objc func update() { let enumerator = mapTable.objectEnumerator() while let any: AnyObject = enumerator?.nextObject() as AnyObject? { if let loopable = any as? WeaklyLoopable { loopable.loopWeakly() } } for (_, closure) in closures { closure() } } func register(_ closure: @escaping Closure, forKey key: String) { closures[key] = closure start() } func register(_ loopable: WeaklyLoopable, forKey key: String) { mapTable.setObject(loopable as AnyObject?, forKey: key as AnyObject?) start() } func unregister(_ key: String) { mapTable.removeObject(forKey: key as AnyObject?) closures.removeValue(forKey: key) if mapTable.count == 0 && closures.isEmpty { stop() } } func contains(_ key: String) -> Bool { return mapTable.object(forKey: key as AnyObject?) != nil || closures[key] != nil } }
apache-2.0
132121f0a4bf43a57cae9bc42b2c8ac1
24.604938
157
0.572324
4.724374
false
false
false
false
JustForFunOrg/4-TipCalculator
TipCalculator/MainViewController.swift
1
3254
// // ViewController.swift // TipCalculator // // Created by vmalikov on 1/30/16. // Copyright © 2016 justForFun. All rights reserved. // import UIKit class MainViewController: UIViewController { @IBOutlet weak var amountTextField: UITextField! @IBOutlet weak var tipPercentLabel: UILabel! @IBOutlet weak var tipResultLabel: UILabel! @IBOutlet weak var totalResultLabel: UILabel! @IBOutlet weak var tipPercentSlider: UISlider! override func viewDidLoad() { super.viewDidLoad() amountTextField.delegate = self amountTextField.resignFirstResponder() addDoneButtonToKeyboard() } // MARK: Keyboard func addDoneButtonToKeyboard() { let numberToolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.frame.size.width, 50)) numberToolbar.barStyle = UIBarStyle.Default numberToolbar.items = [ UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil), UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "keyboardDoneButtonTapped")] numberToolbar.sizeToFit() amountTextField.inputAccessoryView = numberToolbar } func keyboardDoneButtonTapped() { amountTextField.endEditing(true) textFieldDidEndEditing(amountTextField) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { amountTextField.resignFirstResponder() } // MARK: Helpers func updateTipPersentLabel() { let percentValue = Int(tipPercentSlider.value) tipPercentLabel.text = "Tip (\(percentValue)%)" } func updateTipResultLabel() { tipResultLabel.text = "\(getTipAmount().formatWithDefaultValue())" } func updateTotalLabel() { totalResultLabel.text = "\(getCalculatedTotal().formatWithDefaultValue())" } @IBAction func percentSliderValueChanged(sender: UISlider) { updateTipPersentLabel() updateTipResultLabel() updateTotalLabel() } func getTipAmount() -> Float { let percent = floor(tipPercentSlider.value) return getAmount() * (percent / 100) } func getAmount() -> Float { guard var amountString = amountTextField.text where amountString.characters.count > 0 else { return 0 } amountString = amountString.stringByReplacingOccurrencesOfString("$", withString: "") if let amount = Float(amountString) { return amount } else { return 0 } } func getCalculatedTotal() -> Float { return getAmount() + getTipAmount() } } // MARK: - UITextFieldDelegate extension MainViewController : UITextFieldDelegate { func textFieldDidEndEditing(textField: UITextField) { textField.text = "\(getAmount().formatWithDefaultValue())" updateTipPersentLabel() updateTipResultLabel() updateTotalLabel() } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.endEditing(true) return true } }
mit
473126c4ae305ab75f46448e6bc5d203
26.567797
128
0.642484
5.272285
false
false
false
false
delannoyk/SoundcloudSDK
sources/SoundcloudSDK/request/UserRequest.swift
1
17489
// // UserRequest.swift // SoundcloudSDK // // Created by Kevin DELANNOY on 25/04/15. // Copyright (c) 2015 Kevin Delannoy. All rights reserved. // import Foundation extension User { static let BaseURL = URL(string: "https://api.soundcloud.com/users")! /** Loads an user profile - parameter identifier: The identifier of the user to load - parameter completion: The closure that will be called when user profile is loaded or upon error */ @discardableResult public static func user(identifier: Int, completion: @escaping (SimpleAPIResponse<User>) -> Void) -> CancelableOperation? { guard let clientIdentifier = SoundcloudClient.clientIdentifier else { completion(SimpleAPIResponse(error: .credentialsNotSet)) return nil } let url = BaseURL.appendingPathComponent("\(identifier).json") let parameters = ["client_id": clientIdentifier] let request = Request(url: url, method: .get, parameters: parameters, parse: { if let user = User(JSON: $0) { return .success(user) } return .failure(.parsing) }) { result in completion(SimpleAPIResponse(result: result)) } request.start() return request } /** Search users that fit requested name. - parameter query: The query to run. - parameter completion: The closure that will be called when users are loaded or upon error. */ @discardableResult public static func search(query: String, completion: @escaping (PaginatedAPIResponse<User>) -> Void) -> CancelableOperation? { guard let clientIdentifier = SoundcloudClient.clientIdentifier else { completion(PaginatedAPIResponse(error: .credentialsNotSet)) return nil } let parse = { (JSON: JSONObject) -> Result<[User], SoundcloudError> in guard let users = JSON.flatMap(transform: { User(JSON: $0) }) else { return .failure(.parsing) } return .success(users) } let parameters = ["client_id": clientIdentifier, "linked_partitioning": "true", "q": query] let request = Request(url: BaseURL, method: .get, parameters: parameters, parse: { JSON -> Result<PaginatedAPIResponse<User>, SoundcloudError> in return .success(PaginatedAPIResponse(JSON: JSON, parse: parse)) }) { result in completion(result.recover { PaginatedAPIResponse(error: $0) }) } request.start() return request } /** Loads tracks the user uploaded to Soundcloud - parameter completion: The closure that will be called when tracks are loaded or upon error */ @discardableResult public func tracks(completion: @escaping (PaginatedAPIResponse<Track>) -> Void) -> CancelableOperation? { return User.tracks(from: identifier, completion: completion) } /** Loads tracks the user uploaded to Soundcloud - parameter userIdentifier: The identifier of the user to load - parameter completion: The closure that will be called when tracks are loaded or upon error */ @discardableResult public static func tracks(from userIdentifier: Int, completion: @escaping (PaginatedAPIResponse<Track>) -> Void) -> CancelableOperation? { guard let clientIdentifier = SoundcloudClient.clientIdentifier else { completion(PaginatedAPIResponse(error: .credentialsNotSet)) return nil } let url = BaseURL.appendingPathComponent("\(userIdentifier)/tracks.json") var parameters = ["client_id": clientIdentifier, "linked_partitioning": "true"] #if !os(tvOS) if let oauthToken = SoundcloudClient.session?.accessToken { parameters["oauth_token"] = oauthToken } #endif let parse = { (JSON: JSONObject) -> Result<[Track], SoundcloudError> in guard let tracks = JSON.flatMap(transform: { Track(JSON: $0) }) else { return .failure(.parsing) } return .success(tracks) } let request = Request(url: url, method: .get, parameters: parameters, parse: { JSON -> Result<PaginatedAPIResponse<Track>, SoundcloudError> in return .success(PaginatedAPIResponse(JSON: JSON, parse: parse)) }) { result in completion(result.recover { PaginatedAPIResponse(error: $0) }) } request.start() return request } /** Load all comments from the user - parameter completion: The closure that will be called when the comments are loaded or upon error */ @discardableResult public func comments(completion: @escaping (PaginatedAPIResponse<Comment>) -> Void) -> CancelableOperation? { return User.comments(from: identifier, completion: completion) } /** Load all comments from the user - parameter userIdentifier: The user identifier - parameter completion: The closure that will be called when the comments are loaded or upon error */ @discardableResult public static func comments(from userIdentifier: Int, completion: @escaping (PaginatedAPIResponse<Comment>) -> Void) -> CancelableOperation? { guard let clientIdentifier = SoundcloudClient.clientIdentifier else { completion(PaginatedAPIResponse(error: .credentialsNotSet)) return nil } let url = BaseURL.appendingPathComponent("\(userIdentifier)/comments.json") let parameters = ["client_id": clientIdentifier, "linked_partitioning": "true"] let parse = { (JSON: JSONObject) -> Result<[Comment], SoundcloudError> in guard let comments = JSON.flatMap(transform: { Comment(JSON: $0) }) else { return .failure(.parsing) } return .success(comments) } let request = Request(url: url, method: .get, parameters: parameters, parse: { JSON -> Result<PaginatedAPIResponse<Comment>, SoundcloudError> in return .success(PaginatedAPIResponse(JSON: JSON, parse: parse)) }) { result in completion(result.recover { PaginatedAPIResponse(error: $0) }) } request.start() return request } /** Loads favorited tracks of the user - parameter completion: The closure that will be called when tracks are loaded or upon error */ @discardableResult public func favorites(completion: @escaping (PaginatedAPIResponse<Track>) -> Void) -> CancelableOperation? { return User.favorites(from: identifier, completion: completion) } /** Loads favorited tracks of the user - parameter userIdentifier: The user identifier - parameter completion: The closure that will be called when tracks are loaded or upon error */ @discardableResult public static func favorites(from userIdentifier: Int, completion: @escaping (PaginatedAPIResponse<Track>) -> Void) -> CancelableOperation? { guard let clientIdentifier = SoundcloudClient.clientIdentifier else { completion(PaginatedAPIResponse(error: .credentialsNotSet)) return nil } let url = BaseURL.appendingPathComponent("\(userIdentifier)/favorites.json") let parameters = ["client_id": clientIdentifier, "linked_partitioning": "true"] let parse = { (JSON: JSONObject) -> Result<[Track], SoundcloudError> in guard let tracks = JSON.flatMap(transform: { Track(JSON: $0) }) else { return .failure(.parsing) } return .success(tracks) } let request = Request(url: url, method: .get, parameters: parameters, parse: { JSON -> Result<PaginatedAPIResponse<Track>, SoundcloudError> in return .success(PaginatedAPIResponse(JSON: JSON, parse: parse)) }) { result in completion(result.recover { PaginatedAPIResponse(error: $0) }) } request.start() return request } /** Loads followers of the user - parameter completion: The closure that will be called when followers are loaded or upon error */ @discardableResult public func followers(completion: @escaping (PaginatedAPIResponse<User>) -> Void) -> CancelableOperation? { return User.followers(from: identifier, completion: completion) } /** Loads followers of the user - parameter userIdentifier: The user identifier - parameter completion: The closure that will be called when followers are loaded or upon error */ @discardableResult public static func followers(from userIdentifier: Int, completion: @escaping (PaginatedAPIResponse<User>) -> Void) -> CancelableOperation? { guard let clientIdentifier = SoundcloudClient.clientIdentifier else { completion(PaginatedAPIResponse(error: .credentialsNotSet)) return nil } let url = User.BaseURL.appendingPathComponent("\(userIdentifier)/followers.json") let parameters = ["client_id": clientIdentifier, "linked_partitioning": "true"] let parse = { (JSON: JSONObject) -> Result<[User], SoundcloudError> in guard let users = JSON.flatMap(transform: { User(JSON: $0) }) else { return .failure(.parsing) } return .success(users) } let request = Request(url: url, method: .get, parameters: parameters, parse: { JSON -> Result<PaginatedAPIResponse<User>, SoundcloudError> in return .success(PaginatedAPIResponse(JSON: JSON, parse: parse)) }) { result in completion(result.recover { PaginatedAPIResponse(error: $0) }) } request.start() return request } /** Loads followed users of the user - parameter completion: The closure that will be called when followed users are loaded or upon error */ @discardableResult public func followings(completion: @escaping (PaginatedAPIResponse<User>) -> Void) -> CancelableOperation? { return User.followings(from: identifier, completion: completion) } /** Loads followed users of the user - parameter userIdentifier: The user identifier - parameter completion: The closure that will be called when followed users are loaded or upon error */ @discardableResult public static func followings(from userIdentifier: Int, completion: @escaping (PaginatedAPIResponse<User>) -> Void) -> CancelableOperation? { guard let clientIdentifier = SoundcloudClient.clientIdentifier else { completion(PaginatedAPIResponse(error: .credentialsNotSet)) return nil } let url = User.BaseURL.appendingPathComponent("\(userIdentifier)/followings.json") let parameters = ["client_id": clientIdentifier, "linked_partitioning": "true"] let parse = { (JSON: JSONObject) -> Result<[User], SoundcloudError> in guard let users = JSON.flatMap(transform: { User(JSON: $0) }) else { return .failure(.parsing) } return .success(users) } let request = Request(url: url, method: .get, parameters: parameters, parse: { JSON -> Result<PaginatedAPIResponse<User>, SoundcloudError> in return .success(PaginatedAPIResponse(JSON: JSON, parse: parse)) }) { result in completion(result.recover { PaginatedAPIResponse(error: $0) }) } request.start() return request } /** Follow the given user. **This method requires a Session.** - parameter userIdentifier: The identifier of the user to follow - parameter completion: The closure that will be called when the user has been followed or upon error */ @discardableResult @available(tvOS, unavailable) public func follow(userIdentifier: Int, completion: @escaping (SimpleAPIResponse<Bool>) -> Void) -> CancelableOperation? { #if !os(tvOS) return User.changeFollowStatus(follow: true, userIdentifier: userIdentifier, completion: completion) #else return nil #endif } /** Follow the given user. **This method requires a Session.** - parameter userIdentifier: The identifier of the user to follow - parameter completion: The closure that will be called when the user has been followed or upon error */ @discardableResult @available(tvOS, unavailable) public static func follow(userIdentifier: Int, completion: @escaping (SimpleAPIResponse<Bool>) -> Void) -> CancelableOperation? { #if !os(tvOS) return User.changeFollowStatus(follow: true, userIdentifier: userIdentifier, completion: completion) #else return nil #endif } /** Unfollow the given user. **This method requires a Session.** - parameter userIdentifier: The identifier of the user to unfollow - parameter completion: The closure that will be called when the user has been unfollowed or upon error */ @discardableResult @available(tvOS, unavailable) public func unfollow(userIdentifier: Int, completion: @escaping (SimpleAPIResponse<Bool>) -> Void) -> CancelableOperation? { #if !os(tvOS) return User.changeFollowStatus(follow: false, userIdentifier: userIdentifier, completion: completion) #else return nil #endif } /** Unfollow the given user. **This method requires a Session.** - parameter userIdentifier: The identifier of the user to unfollow - parameter completion: The closure that will be called when the user has been unfollowed or upon error */ @discardableResult @available(tvOS, unavailable) public static func unfollow(userIdentifier: Int, completion: @escaping (SimpleAPIResponse<Bool>) -> Void) -> CancelableOperation? { #if !os(tvOS) return User.changeFollowStatus(follow: false, userIdentifier: userIdentifier, completion: completion) #else return nil #endif } @available(tvOS, unavailable) private static func changeFollowStatus(follow: Bool, userIdentifier: Int, completion: @escaping (SimpleAPIResponse<Bool>) -> Void) -> CancelableOperation? { #if !os(tvOS) guard let clientIdentifier = SoundcloudClient.clientIdentifier else { completion(SimpleAPIResponse(error: .credentialsNotSet)) return nil } guard let oauthToken = SoundcloudClient.session?.accessToken else { completion(SimpleAPIResponse(error: .needsLogin)) return nil } let parameters = ["client_id": clientIdentifier, "oauth_token": oauthToken] let url = BaseURL .deletingLastPathComponent() .appendingPathComponent("me/followings/\(userIdentifier).json") .appendingQueryString(parameters.queryString) let request = Request(url: url, method: follow ? .put : .delete, parameters: nil, parse: { _ in return .success(true) }) { result in completion(SimpleAPIResponse(result: result)) } request.start() return request #else return nil #endif } /** Loads user's playlists - parameter completion: The closure that will be called when playlists has been loaded or upon error */ @discardableResult public func playlists(completion: @escaping (PaginatedAPIResponse<Playlist>) -> Void) -> CancelableOperation? { return User.playlists(from: identifier, completion: completion) } /** Loads user's playlists - parameter userIdentifier: The identifier of the user to unfollow - parameter completion: The closure that will be called when playlists has been loaded or upon error */ @discardableResult public static func playlists(from userIdentifier: Int, completion: @escaping (PaginatedAPIResponse<Playlist>) -> Void) -> CancelableOperation? { guard let clientIdentifier = SoundcloudClient.clientIdentifier else { completion(PaginatedAPIResponse(error: .credentialsNotSet)) return nil } let url = BaseURL.appendingPathComponent("\(userIdentifier)/playlists.json") var parameters = ["client_id": clientIdentifier, "linked_partitioning": "true"] #if !os(tvOS) if let oauthToken = SoundcloudClient.session?.accessToken { parameters["oauth_token"] = oauthToken } #endif let parse = { (JSON: JSONObject) -> Result<[Playlist], SoundcloudError> in guard let playlists = JSON.flatMap(transform: { Playlist(JSON: $0) }) else { return .failure(.parsing) } return .success(playlists) } let request = Request(url: url, method: .get, parameters: parameters, parse: { JSON -> Result<PaginatedAPIResponse<Playlist>, SoundcloudError> in return .success(PaginatedAPIResponse(JSON: JSON, parse: parse)) }) { result in completion(result.recover { PaginatedAPIResponse(error: $0) }) } request.start() return request } }
mit
b764e27c93bfba76ce589960e4209325
39.112385
160
0.645034
5.016925
false
false
false
false
Allow2CEO/browser-ios
brave/src/frontend/PinController.swift
1
17472
/* 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 UIKit import Foundation import Shared import LocalAuthentication import SwiftKeychainWrapper import AudioToolbox public let KeychainKeyPinLockInfo = "pinLockInfo" struct PinUX { fileprivate static var ButtonSize: CGSize { let size = DeviceDetector.iPhone4s ? 60 : 80 return CGSize(width: size, height: size) } fileprivate static let DefaultForegroundColor = UIColor(rgb: 0x4a4a4a) fileprivate static let DefaultBackgroundColor = UIColor(rgb: 0x4a4a4a).withAlphaComponent(0.1) fileprivate static let SelectedBackgroundColor = BraveUX.BraveOrange fileprivate static let DefaultBorderWidth: CGFloat = 0.0 fileprivate static let SelectedBorderWidth: CGFloat = 0.0 fileprivate static let DefaultBorderColor = UIColor(rgb: 0x4a4a4a).cgColor fileprivate static let IndicatorSize: CGSize = CGSize(width: 14, height: 14) fileprivate static let IndicatorSpacing: CGFloat = 17.0 } protocol PinViewControllerDelegate { func pinViewController(_ completed: Bool) -> Void } class PinViewController: UIViewController, PinViewControllerDelegate { var delegate: PinViewControllerDelegate? var pinView: PinLockView! static var isBrowserLockEnabled: Bool { let profile = getApp().profile return profile?.prefs.boolForKey(kPrefKeySetBrowserLock) == true || profile?.prefs.boolForKey(kPrefKeyPopupForBrowserLock) == true } override func loadView() { super.loadView() pinView = PinLockView(message: Strings.PinNew) pinView.codeCallback = { code in let view = ConfirmPinViewController() view.delegate = self view.initialPin = code self.navigationController?.pushViewController(view, animated: true) } view.addSubview(pinView) let pinViewSize = pinView.frame.size pinView.snp.makeConstraints { (make) in make.size.equalTo(pinViewSize) make.centerX.equalTo(self.view.center).offset(0) let offset = UIScreen.main.bounds.height < 667 ? 30 : 0 make.centerY.equalTo(self.view.center).offset(offset) } title = Strings.PinSet view.backgroundColor = UIColor(rgb: 0xF8F8F8) } func pinViewController(_ completed: Bool) { delegate?.pinViewController(completed) } } class ConfirmPinViewController: UIViewController { var delegate: PinViewControllerDelegate? var pinView: PinLockView! var initialPin: String = "" override func loadView() { super.loadView() pinView = PinLockView(message: Strings.PinNewRe) pinView.codeCallback = { code in if code == self.initialPin { let pinLockInfo = AuthenticationKeychainInfo(passcode: code) if LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { pinLockInfo.useTouchID = true } KeychainWrapper.setPinLockInfo(pinLockInfo) self.delegate?.pinViewController(true) self.navigationController?.popToRootViewController(animated: true) } else { self.pinView.tryAgain() } } view.addSubview(pinView) let pinViewSize = pinView.frame.size pinView.snp.makeConstraints { (make) in make.size.equalTo(pinViewSize) make.centerX.equalTo(self.view.center).offset(0) let offset = UIScreen.main.bounds.height < 667 ? 30 : 0 make.centerY.equalTo(self.view.center).offset(offset) } title = Strings.PinSet view.backgroundColor = UIColor(rgb: 0xF8F8F8) navigationItem.leftBarButtonItem = UIBarButtonItem(title: Strings.Cancel, style: .plain, target: self, action: #selector(SEL_cancel)) } func SEL_cancel() { navigationController?.popToRootViewController(animated: true) delegate?.pinViewController(false) } } class PinProtectOverlayViewController: UIViewController { var blur: UIVisualEffectView! var pinView: PinLockView! var touchCanceled: Bool = false var successCallback: ((_ success: Bool) -> Void)? var attempts: Int = 0 override func loadView() { super.loadView() blur = UIVisualEffectView(effect: UIBlurEffect(style: .light)) view.addSubview(blur) pinView = PinLockView(message: Strings.PinEnterToUnlock) pinView.codeCallback = { code in if let pinLockInfo = KeychainWrapper.pinLockInfo() { if code == pinLockInfo.passcode { self.successCallback?(true) self.pinView.reset() } else { self.successCallback?(false) self.attempts += 1 self.pinView.tryAgain() } } } view.addSubview(pinView) let pinViewSize = pinView.frame.size pinView.snp.makeConstraints { (make) in make.size.equalTo(pinViewSize) make.center.equalTo(self.view.center).offset(0) } blur.snp.makeConstraints { (make) in make.edges.equalTo(self.view) } start() } override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } override var shouldAutorotate : Bool { return false } override var preferredInterfaceOrientationForPresentation : UIInterfaceOrientation { return UIInterfaceOrientation.portrait } func start() { getApp().browserViewController.view.endEditing(true) pinView.isHidden = true touchCanceled = false } func auth() { if touchCanceled { return } var authError: NSError? = nil let authenticationContext = LAContext() if authenticationContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError) { authenticationContext.evaluatePolicy( .deviceOwnerAuthenticationWithBiometrics, localizedReason: Strings.PinFingerprintUnlock, reply: { [unowned self] (success, error) -> Void in if success { self.successCallback?(true) } else { self.touchCanceled = true postAsyncToMain { self.pinView.isHidden = false } } }) } else { self.touchCanceled = true postAsyncToMain { self.pinView.isHidden = false } } } } class PinLockView: UIView { var buttons: [PinButton] = [] var codeCallback: ((_ code: String) -> Void)? var messageLabel: UILabel! var pinIndicatorView: PinIndicatorView! var deleteButton: UIButton! var pin: String = "" convenience init(message: String) { self.init() messageLabel = UILabel() messageLabel.text = message messageLabel.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightMedium) messageLabel.textColor = PinUX.DefaultForegroundColor messageLabel.sizeToFit() addSubview(messageLabel) pinIndicatorView = PinIndicatorView(size: 4) pinIndicatorView.sizeToFit() pinIndicatorView.index(0) addSubview(pinIndicatorView) for i in 1...10 { let button = PinButton() button.tag = i button.titleLabel.text = i == 10 ? "0" : "\(i)" button.addTarget(self, action: #selector(SEL_pinButton(_:)), for: .touchUpInside) addSubview(button) buttons.append(button) } deleteButton = UIButton() deleteButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightMedium) deleteButton.setTitle(Strings.Delete, for: .normal) deleteButton.setTitleColor(PinUX.DefaultForegroundColor, for: .normal) deleteButton.setTitleColor(BraveUX.GreyJ, for: .highlighted) deleteButton.addTarget(self, action: #selector(SEL_delete(_:)), for: .touchUpInside) deleteButton.sizeToFit() addSubview(deleteButton) layoutSubviews() sizeToFit() } override func layoutSubviews() { let spaceX: CGFloat = (min(350, UIScreen.main.bounds.width) - PinUX.ButtonSize.width * 3) / 4 // Special care for iPhone 4s to make all elements fit on screen. let spaceY: CGFloat = DeviceDetector.iPhone4s ? spaceX - 20 : spaceX let w: CGFloat = PinUX.ButtonSize.width let h: CGFloat = PinUX.ButtonSize.height let frameWidth = spaceX * 2 + w * 3 var messageLabelFrame = messageLabel.frame messageLabelFrame.origin.x = (frameWidth - messageLabelFrame.width) / 2 messageLabelFrame.origin.y = 0 messageLabel.frame = messageLabelFrame var indicatorViewFrame = pinIndicatorView.frame indicatorViewFrame.origin.x = (frameWidth - indicatorViewFrame.width) / 2 indicatorViewFrame.origin.y = messageLabelFrame.maxY + 18 pinIndicatorView.frame = indicatorViewFrame var x: CGFloat = 0 var y: CGFloat = indicatorViewFrame.maxY + spaceY for i in 0..<buttons.count { if i == buttons.count - 1 { // Center last. x = (frameWidth - w) / 2 } let button = buttons[i] var buttonFrame = button.frame buttonFrame.origin.x = rint(x) buttonFrame.origin.y = rint(y) buttonFrame.size.width = w buttonFrame.size.height = h button.frame = buttonFrame x = x + w + spaceX if x > frameWidth { x = 0 y = y + h + spaceY } } let button0 = viewWithTag(10) let button9 = viewWithTag(9) var deleteButtonFrame = deleteButton.frame deleteButtonFrame.center = CGPoint(x: rint((button9?.frame ?? CGRect.zero).midX), y: rint((button0?.frame ?? CGRect.zero).midY)) deleteButton.frame = deleteButtonFrame } override func sizeToFit() { let button0 = buttons[buttons.count - 1] let button9 = buttons[buttons.count - 2] let w = button9.frame.maxX let h = button0.frame.maxY var f = bounds f.size.width = w f.size.height = h frame = f bounds = CGRect(x: 0, y: 0, width: w, height: h) } func SEL_pinButton(_ sender: UIButton) { if pin.characters.count < 4 { let value = sender.tag == 10 ? 0 : sender.tag pin = pin + "\(value)" } pinIndicatorView.index(pin.characters.count) if pin.characters.count == 4 && codeCallback != nil { codeCallback!(pin) } } func SEL_delete(_ sender: UIButton) { if pin.characters.count > 0 { pin = pin.substring(to: pin.characters.index(pin.endIndex, offsetBy: -1)) pinIndicatorView.index(pin.characters.count) } } func reset() { pinIndicatorView.index(0) pin = "" } func tryAgain() { AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) let animation = CABasicAnimation(keyPath: "position") animation.duration = 0.06 animation.repeatCount = 3 animation.autoreverses = true animation.fromValue = NSValue(cgPoint: CGPoint(x: pinIndicatorView.frame.midX - 10, y: pinIndicatorView.frame.midY)) animation.toValue = NSValue(cgPoint: CGPoint(x: pinIndicatorView.frame.midX + 10, y: pinIndicatorView.frame.midY)) pinIndicatorView.layer.add(animation, forKey: "position") self.perform(#selector(reset), with: self, afterDelay: 0.4) } } class PinIndicatorView: UIView { var indicators: [UIView] = [] var defaultColor: UIColor! convenience init(size: Int) { self.init() defaultColor = PinUX.DefaultForegroundColor for i in 0..<size { let view = UIView() view.tag = i view.layer.cornerRadius = PinUX.IndicatorSize.width / 2 view.layer.masksToBounds = true view.layer.borderWidth = 1 view.layer.borderColor = defaultColor.cgColor view.backgroundColor = PinUX.DefaultBackgroundColor addSubview(view) indicators.append(view) } setNeedsDisplay() layoutIfNeeded() } override func layoutSubviews() { let spaceX: CGFloat = PinUX.IndicatorSpacing var x: CGFloat = 0 for i in 0..<indicators.count { let view = indicators[i] var viewFrame = view.frame viewFrame.origin.x = x viewFrame.origin.y = 0 viewFrame.size.width = PinUX.IndicatorSize.width viewFrame.size.height = PinUX.IndicatorSize.height view.frame = viewFrame x = x + PinUX.IndicatorSize.width + spaceX } } override func sizeToFit() { let view = indicators[indicators.count - 1] var f = frame f.size.width = view.frame.maxX f.size.height = view.frame.maxY frame = f } func index(_ index: Int) -> Void { if index > indicators.count { return } // Fill for i in 0..<index { let view = indicators[i] view.backgroundColor = PinUX.SelectedBackgroundColor view.layer.borderColor = PinUX.SelectedBackgroundColor.cgColor } // Clear additional if index < indicators.count { for i in index..<indicators.count { let view = indicators[i] view.layer.borderWidth = PinUX.DefaultBorderWidth view.layer.borderColor = PinUX.DefaultBorderColor view.backgroundColor = PinUX.DefaultBackgroundColor } } // Outline next if index < indicators.count { let view = indicators[index] view.layer.borderWidth = 2 } } } class PinButton: UIControl { var titleLabel: UILabel! override init(frame: CGRect) { super.init(frame: frame) layer.masksToBounds = true layer.borderWidth = PinUX.DefaultBorderWidth layer.borderColor = PinUX.DefaultBorderColor backgroundColor = PinUX.DefaultBackgroundColor titleLabel = UILabel(frame: frame) titleLabel.isUserInteractionEnabled = false titleLabel.textAlignment = .center titleLabel.font = UIFont.systemFont(ofSize: 30, weight: UIFontWeightMedium) titleLabel.textColor = PinUX.DefaultForegroundColor titleLabel.backgroundColor = UIColor.clear addSubview(titleLabel) setNeedsDisplay() } required init(coder: NSCoder) { super.init(coder: coder)! } override var isHighlighted: Bool { didSet { if (isHighlighted) { backgroundColor = PinUX.SelectedBackgroundColor titleLabel.textColor = UIColor.white layer.borderColor = PinUX.SelectedBackgroundColor.cgColor } else { backgroundColor = PinUX.DefaultBackgroundColor titleLabel.textColor = PinUX.DefaultForegroundColor layer.borderColor = PinUX.DefaultBorderColor } } } override func layoutSubviews() { titleLabel.frame = bounds layer.cornerRadius = frame.height / 2.0 } override func sizeToFit() { super.sizeToFit() var frame: CGRect = self.frame frame.size.width = PinUX.ButtonSize.width frame.size.height = PinUX.ButtonSize.height self.frame = frame } } extension KeychainWrapper { class func pinLockInfo() -> AuthenticationKeychainInfo? { NSKeyedUnarchiver.setClass(AuthenticationKeychainInfo.self, forClassName: "AuthenticationKeychainInfo") return KeychainWrapper.standard.object(forKey: KeychainKeyPinLockInfo) as? AuthenticationKeychainInfo } class func setPinLockInfo(_ info: AuthenticationKeychainInfo?) { NSKeyedArchiver.setClassName("AuthenticationKeychainInfo", for: AuthenticationKeychainInfo.self) if let info = info { KeychainWrapper.standard.set(info, forKey: KeychainKeyPinLockInfo) } else { KeychainWrapper.standard.removeObject(forKey: KeychainKeyPinLockInfo) } } }
mpl-2.0
8393daef2ca2caa9b3375715a58808f5
33.258824
198
0.5985
5.00487
false
false
false
false
emiledecosterd/Reachability
Reachability/Controllers/ReachabilityController.swift
1
6641
/* * Copyright (c) 2016 Emile Décosterd * * 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 // MARK: Base class // MARK: - ///A class that takes care of everything related to the internet reachability final class ReachabilityController { // MARK: Properties //Model fileprivate var reachabilityManager: ReachabilityManager fileprivate var banner: ReachabilityBanner! = nil{ // Created at initialisation didSet{ showBannerForSeconds(3) } } // Views fileprivate unowned var view: UIView fileprivate let bannerView: BannerView public var shouldShowBanner: Bool = true // Set this to false if you do not want the banner to show // Helpers fileprivate var bannerWidth: CGFloat { return UIScreen.main.bounds.size.width } fileprivate var bannerHeight = CGFloat(44) // MARK: Initialisation /** * Instanciates a `ReachabilityController`. * * - Parameter view: The view in which to show a banner view when reachability changes. The banner will be displayed on the top of this view. */ init(view: UIView){ // Setup views self.view = view let bannerViewFrame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 0) bannerView = BannerView(frame: bannerViewFrame) // Setup manager reachabilityManager = ReachabilityManager() reachabilityManager.delegate = self reachabilityManager.startMonitoring() banner = ReachabilityBanner(status: reachabilityManager.status) if banner.status != .wifi { showBannerForSeconds(3) } // Respond to orientation changes NotificationCenter.default.addObserver(self, selector: #selector(ReachabilityController.orientationChanged(_:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } /** * Instanciates a `ReachabilityController`. * * - Parameter view: The view in which to show a banner view when reachability changes. The banner will be displayed on the top of this view. * - Parameter wifiOnly: If we want to be informed when we use cellular connection instead of wifi. */ convenience init(view: UIView, wifiOnly: Bool){ self.init(view:view) reachabilityManager.wifiOnly = true } /** * Instanciates a `ReachabilityController`. * * - Parameter view: The view in which to show a banner view when reachability changes. The banner will be displayed on the top of this view. * - Parameter statusBar: If the view contains the status bar, set `statusBar` to `true`. */ convenience init(view: UIView, statusBar: Bool){ self.init(view: view) if statusBar { bannerHeight = CGFloat(64) } } /** * Instanciates a `ReachabilityController`. * * - Parameter view: The view in which to show a banner view when reachability changes. The banner will be displayed on the top of this view. * - Parameter wifiOnly: If we want to be informed when we use cellular connection instead of wifi. * - Parameter statusBar: If the view contains the status bar, set `statusBar` to `true`. */ convenience init(view: UIView, wifiOnly: Bool, statusBar: Bool){ self.init(view: view, wifiOnly: wifiOnly) if statusBar{ bannerHeight = CGFloat(64) } } deinit{ NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } // MARK: Show and hide banner depending on reachability changes fileprivate func showBannerForSeconds(_ duration: TimeInterval){ // In case you do not want the banner to be shown to the user if !shouldShowBanner {return} // Show the view with animation bannerView.setupView(banner) view.addSubview(bannerView) UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 1, options: [.allowUserInteraction, .beginFromCurrentState], animations: { self.bannerView.changeFrame(CGRect(x: 0, y: 0, width: self.bannerWidth, height: self.bannerHeight)) }, completion: { (done) in // Hide it after 2 sec Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(ReachabilityController.timerFinished(_:)), userInfo: true, repeats: false) }) } @objc fileprivate func timerFinished(_ timer: Timer){ timer.invalidate() hideBanner(true) } fileprivate func hideBanner(_ animated: Bool){ // If no banner was to be shown, there will be no views to remove if !shouldShowBanner {return} if animated { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 1, options: [.allowUserInteraction, .beginFromCurrentState], animations: { self.bannerView.changeFrame(CGRect(x: 0, y: 0, width: self.bannerWidth, height: 0)) }, completion: { (ok) in self.bannerView.removeFromSuperview() }) }else{ bannerView.removeFromSuperview() } } @objc fileprivate func orientationChanged(_ notification: Notification){ self.view.layoutIfNeeded() } } // MARK: - ReachabilityDelegate // MARK: - /// An extension of `ReachabilityController` to conform to `ReachabilityManager`'s delegate protocol extension ReachabilityController: ReachabilityDelegate { func reachabilityStatusChanged(_ status: NetworkStatus) { banner = ReachabilityBanner(status: status) } }
mit
8a791919a8e7b2fbc396d4cb3b0c546b
35.284153
185
0.694277
4.699222
false
false
false
false
shohei/firefox-ios
Storage/MockLogins.swift
1
3893
/* 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 public class MockLogins: BrowserLogins, SyncableLogins { private var cache = [Login]() public init(files: FileAccessor) { } public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace) -> Deferred<Result<Cursor<LoginData>>> { let cursor = ArrayCursor(data: cache.filter({ login in return login.protectionSpace.host == protectionSpace.host }).sorted({ (loginA, loginB) -> Bool in return loginA.timeLastUsed > loginB.timeLastUsed }).map({ login in return login as LoginData })) return Deferred(value: Result(success: cursor)) } public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace, withUsername username: String?) -> Deferred<Result<Cursor<LoginData>>> { let cursor = ArrayCursor(data: cache.filter({ login in return login.protectionSpace.host == protectionSpace.host && login.username == username }).sorted({ (loginA, loginB) -> Bool in return loginA.timeLastUsed > loginB.timeLastUsed }).map({ login in return login as LoginData })) return Deferred(value: Result(success: cursor)) } // This method is only here for testing public func getUsageDataForLoginByGUID(guid: GUID) -> Deferred<Result<LoginUsageData>> { let res = cache.filter({ login in return login.guid == guid }).sorted({ (loginA, loginB) -> Bool in return loginA.timeLastUsed > loginB.timeLastUsed })[0] as LoginUsageData return Deferred(value: Result(success: res)) } public func addLogin(login: LoginData) -> Success { if let index = find(cache, login as! Login) { return deferResult(LoginDataError(description: "Already in the cache")) } cache.append(login as! Login) return succeed() } public func updateLoginByGUID(guid: GUID, new: LoginData, significant: Bool) -> Success { // TODO return succeed() } public func updateLogin(login: LoginData) -> Success { if let index = find(cache, login as! Login) { cache[index].timePasswordChanged = NSDate.nowMicroseconds() return succeed() } return deferResult(LoginDataError(description: "Password wasn't cached yet. Can't update")) } public func addUseOfLoginByGUID(guid: GUID) -> Success { if let login = cache.filter({ $0.guid == guid }).first { login.timeLastUsed = NSDate.nowMicroseconds() return succeed() } return deferResult(LoginDataError(description: "Password wasn't cached yet. Can't update")) } public func removeLoginByGUID(guid: GUID) -> Success { let filtered = cache.filter { $0.guid != guid } if filtered.count == cache.count { return deferResult(LoginDataError(description: "Can not remove a password that wasn't stored")) } cache = filtered return succeed() } public func removeAll() -> Success { cache.removeAll(keepCapacity: false) return succeed() } // TODO public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success { return succeed() } public func applyChangedLogin(upstream: Login, timestamp: Timestamp) -> Success { return succeed() } public func markAsSynchronized([GUID], modified: Timestamp) -> Deferred<Result<Timestamp>> { return deferResult(0) } public func markAsDeleted(guids: [GUID]) -> Success { return succeed() } public func onRemovedAccount() -> Success { return succeed() } }
mpl-2.0
a1f9cdcb002be55f35e75d96c4fa6d0d
39.14433
155
0.64449
4.896855
false
false
false
false
inder/ios-ranking-visualization
RankViz/RankViz/MetricsManager.swift
1
3514
// // MetricsManager.swift // Reverse Graph // // Created by Inder Sabharwal on 1/6/15. // Copyright (c) 2015 truquity. All rights reserved. // import Foundation class MetricsMgr { class var sharedInstance: MetricsMgr { struct Static { static let instance: MetricsMgr = MetricsMgr() } return Static.instance } //metrics group name -> display order var _metricsGroups: [String] = [] var _stdMetrics: [String:[MetricMetaInformation]] = [:] var _allMetrics: [String:MetricMetaInformation] = [:] var numSections: Int { return _metricsGroups.count } var metricsGroups: [String] { return _metricsGroups } func getMetricMetaListForSection(let section: Int) -> [MetricMetaInformation]? { if (section >= _metricsGroups.count) { return [] } return _stdMetrics[_metricsGroups[section]] } func getMetricMeta(let section: Int, let row: Int) -> MetricMetaInformation? { var metrics = getMetricMetaListForSection(section) return metrics?[row] } func getMetricMeta(byName name: String) -> MetricMetaInformation? { if (_allMetrics[name] == nil) { println("Metric NOT FOUND \(name)") } return _allMetrics[name] } //price/earnings let PE = MetricMetaInformation(name: "PE Ratio", importance: 2, isHigherBetter: false) //price/book let PB = MetricMetaInformation(name: "PB Ratio", importance: 2, isHigherBetter: false) //deb/equity let DEQ = MetricMetaInformation(name: "Debt/Equity", importance: 2, isHigherBetter: false) //free cash flow let FCF = MetricMetaInformation(name: "FCF", importance: 2, isHigherBetter: true) //PEG Ratio - i am assigning more importance to this metric than others! let PEG = MetricMetaInformation(name: "PEG", importance: 2, isHigherBetter: false) let GAIN1M = MetricMetaInformation(name: "Gain 1M", importance: 2, isHigherBetter: true) let GAIN3M = MetricMetaInformation(name: "Gain 3M", importance: 2, isHigherBetter: true) let PS = MetricMetaInformation(name: "Price/Rev", importance: 2, isHigherBetter: false) let VOLUME = MetricMetaInformation(name: "Avg Vol", importance: 2, isHigherBetter: true) //% change from 50 day moving average. let PC50 = MetricMetaInformation(name: "%Chg50DMA", importance: 2, isHigherBetter: true) let PC200 = MetricMetaInformation(name: "%Chg200DMA", importance: 2, isHigherBetter: true) init() { _stdMetrics["Popular"] = [PE, GAIN1M, GAIN3M] _allMetrics[PE.name] = PE _allMetrics[PEG.name] = PEG _stdMetrics["Basic"] = [PE, GAIN1M, GAIN3M, PS, VOLUME] _allMetrics[PS.name] = PS _allMetrics[VOLUME.name] = VOLUME _allMetrics[PB.name] = PB _allMetrics[DEQ.name] = DEQ _allMetrics[FCF.name] = FCF _allMetrics[PEG.name] = PEG _allMetrics[GAIN1M.name] = GAIN1M _allMetrics[GAIN3M.name] = GAIN3M _allMetrics[PC50.name] = PC50 _allMetrics[PC200.name] = PC200 _metricsGroups = ["Popular", "Basic"] } } //some code about sorting dictionaries // func sortMetricsGroups () { // var arr : [String] = [] // let sortedKeysAndValues = sorted(_metricsGroups) { $0.1 < $1.1 } // for (k, v) in sortedKeysAndValues { // arr.append(k) // } // _sortedSections = arr // }
apache-2.0
0c0f8e5b852ee68cab9ad3f9b7d1a9cf
31.537037
94
0.628059
3.607803
false
false
false
false
Acuant/AcuantiOSMobileSDK
Sample-Swift-App/AcuantiOSSDKSwiftSample/ProgressHUD.swift
2
2974
// // ProgressHUD.swift // AcuantiOSSDKSwiftSample // // Created by Tapas Behera on 7/28/17. // Copyright © 2017 Acuant. All rights reserved. // import UIKit class ProgressHUD: UIVisualEffectView { var text: String? { didSet { label.text = text label.textAlignment = NSTextAlignment.center; label.numberOfLines = 0; label.lineBreakMode = .byWordWrapping label.frame.size.width = 120 label.font = UIFont.systemFont(ofSize: 16.0); } } let activityIndictor: UIActivityIndicatorView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.gray) let label: UILabel = UILabel() let blurEffect = UIBlurEffect(style: .light) let vibrancyView: UIVisualEffectView init(text: String) { self.text = text self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect)) super.init(effect: blurEffect) self.setup() } required init?(coder aDecoder: NSCoder) { self.text = "" self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect)) super.init(coder: aDecoder) self.setup() } func setup() { contentView.addSubview(vibrancyView) contentView.addSubview(activityIndictor) contentView.addSubview(label) activityIndictor.startAnimating() } override func didMoveToSuperview() { super.didMoveToSuperview() if let superview = self.superview { let width = superview.frame.size.width / 2.3 let height: CGFloat = 50.0 self.frame = CGRect(x: superview.frame.size.width / 2 - width / 2, y: superview.frame.height / 2 - height / 2, width: width, height: height) vibrancyView.frame = self.bounds let activityIndicatorSize: CGFloat = 40 activityIndictor.frame = CGRect(x: 5, y: height / 2 - activityIndicatorSize / 2, width: activityIndicatorSize, height: activityIndicatorSize) layer.cornerRadius = 8.0 layer.masksToBounds = true label.text = text label.textAlignment = NSTextAlignment.center label.frame = CGRect(x: activityIndicatorSize + 5, y: 0, width: width - activityIndicatorSize - 15, height: height) label.textColor = UIColor.gray label.font = UIFont.boldSystemFont(ofSize: 16) } } func show() { self.isHidden = false } func hide() { self.isHidden = true } }
apache-2.0
b810f54119aafff30befb7816dd2ba6e
32.404494
118
0.546922
5.243386
false
false
false
false
MxABC/oclearning
swiftLearning/Pods/Alamofire/Source/ResponseSerialization.swift
95
13697
// ResponseSerialization.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // 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 // MARK: ResponseSerializer /** The type in which all response serializers must conform to in order to serialize a response. */ public protocol ResponseSerializerType { /// The type of serialized object to be created by this `ResponseSerializerType`. typealias SerializedObject /// The type of error to be created by this `ResponseSerializer` if serialization fails. typealias ErrorObject: ErrorType /** A closure used by response handlers that takes a request, response, data and error and returns a result. */ var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get } } // MARK: - /** A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object. */ public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType { /// The type of serialized object to be created by this `ResponseSerializer`. public typealias SerializedObject = Value /// The type of error to be created by this `ResponseSerializer` if serialization fails. public typealias ErrorObject = Error /** A closure used by response handlers that takes a request, response, data and error and returns a result. */ public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error> /** Initializes the `ResponseSerializer` instance with the given serialize response closure. - parameter serializeResponse: The closure used to serialize the response. - returns: The new generic response serializer instance. */ public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) { self.serializeResponse = serializeResponse } } // MARK: - Default extension Request { /** Adds a handler to be called once the request has finished. - parameter queue: The queue on which the completion handler is dispatched. - parameter completionHandler: The code to be executed once the request has finished. - returns: The request. */ public func response( queue queue: dispatch_queue_t? = nil, completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self { delegate.queue.addOperationWithBlock { dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(self.request, self.response, self.delegate.data, self.delegate.error) } } return self } /** Adds a handler to be called once the request has finished. - parameter queue: The queue on which the completion handler is dispatched. - parameter responseSerializer: The response serializer responsible for serializing the request, response, and data. - parameter completionHandler: The code to be executed once the request has finished. - returns: The request. */ public func response<T: ResponseSerializerType>( queue queue: dispatch_queue_t? = nil, responseSerializer: T, completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void) -> Self { delegate.queue.addOperationWithBlock { let result = responseSerializer.serializeResponse( self.request, self.response, self.delegate.data, self.delegate.error ) dispatch_async(queue ?? dispatch_get_main_queue()) { let response = Response<T.SerializedObject, T.ErrorObject>( request: self.request, response: self.response, data: self.delegate.data, result: result ) completionHandler(response) } } return self } } // MARK: - Data extension Request { /** Creates a response serializer that returns the associated data as-is. - returns: A data response serializer. */ public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> { return ResponseSerializer { _, response, data, error in guard error == nil else { return .Failure(error!) } if let response = response where response.statusCode == 204 { return .Success(NSData()) } guard let validData = data else { let failureReason = "Data could not be serialized. Input data was nil." let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) return .Failure(error) } return .Success(validData) } } /** Adds a handler to be called once the request has finished. - parameter completionHandler: The code to be executed once the request has finished. - returns: The request. */ public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self { return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) } } // MARK: - String extension Request { /** Creates a response serializer that returns a string initialized from the response data with the specified string encoding. - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1. - returns: A string response serializer. */ public static func stringResponseSerializer( var encoding encoding: NSStringEncoding? = nil) -> ResponseSerializer<String, NSError> { return ResponseSerializer { _, response, data, error in guard error == nil else { return .Failure(error!) } if let response = response where response.statusCode == 204 { return .Success("") } guard let validData = data else { let failureReason = "String could not be serialized. Input data was nil." let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) return .Failure(error) } if let encodingName = response?.textEncodingName where encoding == nil { encoding = CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(encodingName) ) } let actualEncoding = encoding ?? NSISOLatin1StringEncoding if let string = String(data: validData, encoding: actualEncoding) { return .Success(string) } else { let failureReason = "String could not be serialized with encoding: \(actualEncoding)" let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) return .Failure(error) } } } /** Adds a handler to be called once the request has finished. - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1. - parameter completionHandler: A closure to be executed once the request has finished. - returns: The request. */ public func responseString( encoding encoding: NSStringEncoding? = nil, completionHandler: Response<String, NSError> -> Void) -> Self { return response( responseSerializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) } } // MARK: - JSON extension Request { /** Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options. - parameter options: The JSON serialization reading options. `.AllowFragments` by default. - returns: A JSON object response serializer. */ public static func JSONResponseSerializer( options options: NSJSONReadingOptions = .AllowFragments) -> ResponseSerializer<AnyObject, NSError> { return ResponseSerializer { _, response, data, error in guard error == nil else { return .Failure(error!) } if let response = response where response.statusCode == 204 { return .Success(NSNull()) } guard let validData = data where validData.length > 0 else { let failureReason = "JSON could not be serialized. Input data was nil or zero length." let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) return .Failure(error) } do { let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options) return .Success(JSON) } catch { return .Failure(error as NSError) } } } /** Adds a handler to be called once the request has finished. - parameter options: The JSON serialization reading options. `.AllowFragments` by default. - parameter completionHandler: A closure to be executed once the request has finished. - returns: The request. */ public func responseJSON( options options: NSJSONReadingOptions = .AllowFragments, completionHandler: Response<AnyObject, NSError> -> Void) -> Self { return response( responseSerializer: Request.JSONResponseSerializer(options: options), completionHandler: completionHandler ) } } // MARK: - Property List extension Request { /** Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options. - parameter options: The property list reading options. `NSPropertyListReadOptions()` by default. - returns: A property list object response serializer. */ public static func propertyListResponseSerializer( options options: NSPropertyListReadOptions = NSPropertyListReadOptions()) -> ResponseSerializer<AnyObject, NSError> { return ResponseSerializer { _, response, data, error in guard error == nil else { return .Failure(error!) } if let response = response where response.statusCode == 204 { return .Success(NSNull()) } guard let validData = data where validData.length > 0 else { let failureReason = "Property list could not be serialized. Input data was nil or zero length." let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason) return .Failure(error) } do { let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil) return .Success(plist) } catch { return .Failure(error as NSError) } } } /** Adds a handler to be called once the request has finished. - parameter options: The property list reading options. `0` by default. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3 arguments: the URL request, the URL response, the server data and the result produced while creating the property list. - returns: The request. */ public func responsePropertyList( options options: NSPropertyListReadOptions = NSPropertyListReadOptions(), completionHandler: Response<AnyObject, NSError> -> Void) -> Self { return response( responseSerializer: Request.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) } }
mit
2a8e0697df35250deea714f55aaa087e
37.577465
130
0.643885
5.585237
false
false
false
false
icemanbsi/BSDropdown
Pod/Classes/BSDropdown.swift
1
33029
// // BSDropdown.swift // V2.0.3 // // Items selector with a pop up table list view. // You can use a NSMutableArray of NSDictionary for the data source // // Created by Bobby Stenly Irawan ( [email protected] - http://bobbystenly.com ) on 11/21/15. // Copyright © 2015 Bobby Stenly Irawan. All rights reserved. // // New in V2.0.3 // - update to swift 3.0.1 // // New in V2.0.2 // - update to swift 3 // // New in V1.3 // - change viewController into weak var // // New in V1.2 // - added DataSource Protocol for custom tableview cell / layout // - added fixedDisplayedTitle to make the default title fixed (not change even the selected item has changed) import Foundation import UIKit 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 } } public protocol BSDropdownDelegate { func onDropdownSelectedItemChange(_ dropdown: BSDropdown, selectedItem: NSDictionary?) } extension BSDropdownDelegate { func onDropdownSelectedItemChange(_ dropdown: BSDropdown, selectedItem: NSDictionary?) { } } public protocol BSDropdownDataSource { func itemHeightForRowAtIndexPath(_ dropdown: BSDropdown, tableView: UITableView, item: NSDictionary?, indexPath: IndexPath) -> CGFloat func itemForRowAtIndexPath(_ dropdown: BSDropdown, tableView: UITableView, item: NSDictionary?, indexPath: IndexPath) -> UITableViewCell } open class BSDropdown:UIButton, UITableViewDelegate, UITableViewDataSource{ //required attributes open weak var viewController: UIViewController? //--end of required attributes //optional attributes open var delegate: BSDropdownDelegate! open var dataSource: BSDropdownDataSource! open var modalBackgroundColor: UIColor = UIColor(white: 0, alpha: 0.5) open var selectorBackgroundColor: UIColor = UIColor(white: 1, alpha: 1) open var headerBackgroundColor: UIColor = UIColor(white: 0, alpha: 1) open var titleColor: UIColor = UIColor(white: 1, alpha: 1) open var cancelButtonBackgroundColor: UIColor = UIColor(white: 0, alpha: 0) open var doneButtonBackgroundColor: UIColor = UIColor(white: 0, alpha: 0) open var cancelTextColor: UIColor = UIColor(white: 0.8, alpha: 1) open var doneTextColor: UIColor = UIColor(white: 0.8, alpha: 1) open var itemTextColor: UIColor = UIColor(white: 0, alpha: 1) open var itemTintColor: UIColor = UIColor(white: 0, alpha: 0.8) open var titleFont:UIFont? = UIFont(name: "Helvetica", size: 16) open var buttonFont:UIFont? = UIFont(name: "Helvetica", size: 13) open var itemFont:UIFont? = UIFont(name: "Helvetica", size: 13) open var title: String = "title" open var cancelButtonTitle: String = "Cancel" open var doneButtonTitle: String = "Done" open var defaultTitle: String = "Select Item" open var titleKey: String = "title" open var enableSearch: Bool = false open var searchPlaceholder: String = "Search" open var fixedDisplayedTitle: Bool = false open var hideDoneButton: Bool = false //-- end of optional attributes fileprivate var selectedIndex: Int = -1 fileprivate var tempSelectedIndex: Int = -1 fileprivate var data: NSMutableArray? fileprivate var originalData: NSMutableArray? fileprivate var selectorModalView: UIView! fileprivate var selectorView: UIView! fileprivate var selectorHeaderView: UIView! fileprivate var lblSelectorTitleLabel: UILabel! fileprivate var btnSelectorCancel: UIButton! fileprivate var btnSelectorDone: UIButton! fileprivate var selectorTableView: UITableView! fileprivate var searchView: UIView! fileprivate var txtKeyword: UITextField! open func setup(){ if let vc = self.viewController { self.selectorModalView = UIView() self.selectorModalView.backgroundColor = self.modalBackgroundColor self.selectorModalView.translatesAutoresizingMaskIntoConstraints = false vc.view.addSubview(self.selectorModalView) vc.view.addConstraint(NSLayoutConstraint(item: self.selectorModalView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: vc.view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)) vc.view.addConstraint(NSLayoutConstraint(item: self.selectorModalView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: vc.view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)) vc.view.addConstraint(NSLayoutConstraint(item: self.selectorModalView, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: vc.view, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: 0)) vc.view.addConstraint(NSLayoutConstraint(item: self.selectorModalView, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: vc.view, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 0)) self.selectorView = UIView() self.selectorView.backgroundColor = self.selectorBackgroundColor self.selectorView.translatesAutoresizingMaskIntoConstraints = false self.selectorModalView.addSubview(self.selectorView) self.selectorModalView.addConstraint(NSLayoutConstraint(item: self.selectorView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.selectorModalView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 50)) self.selectorModalView.addConstraint(NSLayoutConstraint(item: self.selectorView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.selectorModalView, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: -50)) self.selectorModalView.addConstraint(NSLayoutConstraint(item: self.selectorView, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.selectorModalView, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 25)) self.selectorModalView.addConstraint(NSLayoutConstraint(item: self.selectorView, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.selectorModalView, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: -25)) self.selectorHeaderView = UIView() self.selectorHeaderView.backgroundColor = self.headerBackgroundColor self.selectorHeaderView.translatesAutoresizingMaskIntoConstraints = false self.selectorView.addSubview(self.selectorHeaderView) self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorHeaderView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.selectorView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)) self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorHeaderView, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.selectorView, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 0)) self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorHeaderView, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.selectorView, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: 0)) self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorHeaderView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 56)) self.lblSelectorTitleLabel = UILabel() self.lblSelectorTitleLabel.text = self.title self.lblSelectorTitleLabel.textColor = self.titleColor if let font = self.titleFont { self.lblSelectorTitleLabel.font = font } self.lblSelectorTitleLabel.translatesAutoresizingMaskIntoConstraints = false self.selectorHeaderView.addSubview(self.lblSelectorTitleLabel) self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.lblSelectorTitleLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.selectorHeaderView, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)) self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.lblSelectorTitleLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.selectorHeaderView, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)) self.btnSelectorCancel = UIButton() self.btnSelectorCancel.setTitle(self.cancelButtonTitle, for: UIControlState()) self.btnSelectorCancel.titleLabel?.textColor = self.cancelTextColor self.btnSelectorCancel.backgroundColor = self.cancelButtonBackgroundColor self.btnSelectorCancel.titleLabel?.textAlignment = NSTextAlignment.left if let font = self.buttonFont { self.btnSelectorCancel.titleLabel?.font = font } self.btnSelectorCancel.translatesAutoresizingMaskIntoConstraints = false self.selectorHeaderView.addSubview(self.btnSelectorCancel) self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorCancel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.selectorHeaderView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 8)) self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorCancel, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.selectorHeaderView, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: -8)) self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorCancel, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.selectorHeaderView, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 8)) self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorCancel, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 40)) self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorCancel, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 50)) self.btnSelectorDone = UIButton() self.btnSelectorDone.setTitle(self.doneButtonTitle, for: UIControlState()) self.btnSelectorDone.titleLabel?.textColor = self.doneTextColor self.btnSelectorDone.backgroundColor = self.doneButtonBackgroundColor self.btnSelectorDone.titleLabel?.textAlignment = NSTextAlignment.right if let font = self.buttonFont { self.btnSelectorDone.titleLabel?.font = font } self.btnSelectorDone.translatesAutoresizingMaskIntoConstraints = false self.selectorHeaderView.addSubview(self.btnSelectorDone) self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorDone, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.selectorHeaderView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 8)) self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorDone, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.selectorHeaderView, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: -8)) self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorDone, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.selectorHeaderView, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: -8)) self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorDone, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 40)) self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorDone, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 50)) if self.enableSearch { self.searchView = UIView() self.searchView.translatesAutoresizingMaskIntoConstraints = false self.selectorView.addSubview(self.searchView) self.selectorView.addConstraint(NSLayoutConstraint(item: self.searchView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.selectorHeaderView, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)) self.selectorView.addConstraint(NSLayoutConstraint(item: self.searchView, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.selectorView, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 0)) self.selectorView.addConstraint(NSLayoutConstraint(item: self.searchView, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.selectorView, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: 0)) self.selectorView.addConstraint(NSLayoutConstraint(item: self.searchView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 46)) self.txtKeyword = UITextField() self.txtKeyword.borderStyle = .roundedRect self.txtKeyword.translatesAutoresizingMaskIntoConstraints = false self.searchView.addSubview(self.txtKeyword) self.searchView.addConstraint(NSLayoutConstraint(item: self.txtKeyword, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.searchView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 8)) self.searchView.addConstraint(NSLayoutConstraint(item: self.txtKeyword, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.searchView, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: -8)) self.searchView.addConstraint(NSLayoutConstraint(item: self.txtKeyword, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.searchView, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 8)) self.searchView.addConstraint(NSLayoutConstraint(item: self.txtKeyword, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.searchView, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: -8)) self.txtKeyword.placeholder = self.searchPlaceholder self.txtKeyword.font = self.itemFont self.txtKeyword.addTarget(self, action: #selector(BSDropdown.txtKeywordValueChanged(_:)), for: UIControlEvents.editingChanged) } self.selectorTableView = UITableView() self.selectorTableView.translatesAutoresizingMaskIntoConstraints = false self.selectorTableView.delegate = self self.selectorTableView.dataSource = self self.selectorTableView.separatorStyle = .none self.selectorView.addSubview(self.selectorTableView) self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorTableView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.enableSearch ? self.searchView : self.selectorHeaderView, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)) self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorTableView, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.selectorView, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 0)) self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorTableView, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.selectorView, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: 0)) self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorTableView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.selectorView, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)) self.btnSelectorCancel.addTarget(self, action: #selector(BSDropdown.btnSelectorCancelTouched(_:)), for: UIControlEvents.touchUpInside) self.btnSelectorDone.addTarget(self, action: #selector(BSDropdown.btnSelectorDoneTouched(_:)), for: UIControlEvents.touchUpInside) self.addTarget(self, action: #selector(BSDropdown.bsdDropdownClicked(_:)), for: UIControlEvents.touchUpInside) if self.hideDoneButton { self.btnSelectorDone.isHidden = true } self.selectorModalView.isHidden = true self.setTitle(self.defaultTitle, for: UIControlState()) } else{ NSLog("BSDropdown Error : Please set the ViewController first") } } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let values = self.data { return values.count } else{ return 0 } } open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let cellInfoArray = self.data?.object(at: (indexPath as NSIndexPath).row) as! NSDictionary if self.dataSource != nil { return self.dataSource.itemHeightForRowAtIndexPath(self, tableView: tableView, item: cellInfoArray, indexPath: indexPath) } else { let title = cellInfoArray.object(forKey: self.titleKey) as! String let minHeight:CGFloat = 35.0 var height:CGFloat = 16.0 var maxWidth:CGFloat = tableView.bounds.size.width - 16.0 if (indexPath as NSIndexPath).row == self.tempSelectedIndex { maxWidth -= 39.0 } var titleHeight : CGFloat = title.boundingRect( with: CGSize(width: maxWidth, height: 99999), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: self.itemFont!], context: nil ).size.height if titleHeight < 20 { titleHeight = 20 } height += titleHeight return max(minHeight, height) } } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellInfoArray = self.data?.object(at: (indexPath as NSIndexPath).row) as! NSDictionary if self.dataSource != nil { let cell = self.dataSource.itemForRowAtIndexPath(self, tableView: tableView, item: cellInfoArray, indexPath: indexPath) cell.selectionStyle = .none cell.tintColor = self.itemTintColor if (indexPath as NSIndexPath).row == self.tempSelectedIndex { cell.accessoryType = UITableViewCellAccessoryType.checkmark } else{ cell.accessoryType = UITableViewCellAccessoryType.none } return cell } else { let reuseId = "BSDropdownTableViewCell" var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: reuseId) let lblTitle: UILabel! let borderBottom: UIView! if let _ = cell { lblTitle = cell?.viewWithTag(1) as! UILabel borderBottom = cell?.viewWithTag(2) } else{ cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: reuseId) //add label lblTitle = UILabel() lblTitle.translatesAutoresizingMaskIntoConstraints = false cell!.addSubview(lblTitle) cell!.addConstraint(NSLayoutConstraint(item: lblTitle, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: cell, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)) cell!.addConstraint(NSLayoutConstraint(item: lblTitle, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: cell, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 8)) cell!.addConstraint(NSLayoutConstraint(item: lblTitle, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: cell, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: 8)) lblTitle.tag = 1 lblTitle.textColor = self.itemTextColor lblTitle.font = self.itemFont //add border bottom borderBottom = UIView() borderBottom.backgroundColor = UIColor(white: 0.8, alpha: 1) borderBottom.translatesAutoresizingMaskIntoConstraints = false cell!.addSubview(borderBottom) cell!.addConstraint(NSLayoutConstraint(item: borderBottom, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: cell, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0)) cell!.addConstraint(NSLayoutConstraint(item: borderBottom, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: cell, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 0)) cell!.addConstraint(NSLayoutConstraint(item: borderBottom, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: cell, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)) cell!.addConstraint(NSLayoutConstraint(item: borderBottom, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 1)) cell?.selectionStyle = .none cell?.tintColor = self.itemTintColor } lblTitle.text = cellInfoArray.object(forKey: self.titleKey) as? String if (indexPath as NSIndexPath).row == self.tempSelectedIndex { cell?.accessoryType = UITableViewCellAccessoryType.checkmark } else{ cell?.accessoryType = UITableViewCellAccessoryType.none } return cell! } } open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let values = self.data { if (indexPath as NSIndexPath).row > -1 && (indexPath as NSIndexPath).row < values.count { self.tempSelectedIndex = (indexPath as NSIndexPath).row self.selectorTableView.reloadData() if self.hideDoneButton { self.btnSelectorDoneTouched(self.btnSelectorDone) } } } else{ NSLog("BSDropdown Error : Please set the data first") } } open func bsdDropdownClicked(_ sender: AnyObject){ if let vc = self.viewController { self.selectorTableView.reloadData() self.tempSelectedIndex = self.selectedIndex self.selectorModalView.isHidden = false self.selectorModalView.alpha = 0 vc.view.bringSubview(toFront: self.selectorModalView) UIView.animate(withDuration: 0.5, animations: { () -> Void in self.selectorModalView.alpha = 1 }) } } open func btnSelectorCancelTouched(_ sender: AnyObject){ UIView.animate(withDuration: 0.5, animations: { () -> Void in self.selectorModalView.alpha = 0 }, completion: { (Bool) -> Void in self.selectorModalView.isHidden = true if self.enableSearch { self.txtKeyword.text = "" self.filterData("") } }) } open func btnSelectorDoneTouched(_ sender: AnyObject){ self.selectedIndex = self.tempSelectedIndex if self.tempSelectedIndex > -1 && self.tempSelectedIndex < self.data?.count { if let cellInfoArray = self.data?.object(at: self.tempSelectedIndex) as? NSDictionary { if let idx = cellInfoArray.object(forKey: "bsd_index") as? NSNumber { self.selectedIndex = idx.intValue } } } if self.enableSearch { self.txtKeyword.text = "" self.filterData("") } self.setDisplayedTitle() self.btnSelectorCancelTouched(sender) if let d = self.delegate { d.onDropdownSelectedItemChange(self, selectedItem: self.getSelectedValue()) } } fileprivate func setDisplayedTitle(){ //set title if let value = self.getSelectedValue(){ if !self.fixedDisplayedTitle { self.setTitle(value.object(forKey: self.titleKey) as? String, for: UIControlState()) } else { self.setTitle(self.defaultTitle, for: UIControlState()) } } else{ self.setTitle(self.defaultTitle, for: UIControlState()) } } open func txtKeywordValueChanged(_ sender: AnyObject) { self.filterData(self.txtKeyword.text!) self.selectorTableView.reloadData() } fileprivate func filterData(_ keyword: String){ self.data?.removeAllObjects() self.tempSelectedIndex = -1 var i: Int = 0 if let oriData = self.originalData { for item in oriData { if let cellInfoArray = item as? NSMutableDictionary { if keyword == "" || (cellInfoArray.object(forKey: self.titleKey) as! String).lowercased().range( of: keyword.lowercased() ) != nil { cellInfoArray.setValue(NSNumber(value: i as Int), forKey: "bsd_index") self.data?.add(cellInfoArray) } } else if let dict = item as? NSDictionary { let cellInfoArray = NSMutableDictionary(dictionary: dict) if keyword == "" || (cellInfoArray.object(forKey: self.titleKey) as! String).lowercased().range( of: keyword.lowercased() ) != nil { cellInfoArray.setValue(NSNumber(value: i as Int), forKey: "bsd_index") self.data?.add(cellInfoArray) } } else{ NSLog("cellInfoArray invalid : %i", i) } i += 1 } } } //public get set open func setDataSource(_ dataSource: NSMutableArray){ self.originalData = dataSource self.data = NSMutableArray() self.filterData("") } open func setSelectedIndex(_ index: Int){ self.selectedIndex = index self.setDisplayedTitle() } open func getSelectedIndex() -> Int { return self.selectedIndex } open func getSelectedValue() -> NSDictionary?{ if let dataSource = self.originalData { if self.selectedIndex > -1 && self.selectedIndex < dataSource.count{ return dataSource.object(at: self.selectedIndex) as? NSDictionary } else{ return nil } } else{ return nil } } }
mit
0a81ff76d252a57e3bf0218e24fac07c
44.681881
152
0.591226
5.788293
false
false
false
false
li1024316925/Swift-TimeMovie
Swift-TimeMovie/Swift-TimeMovie/AttentionCell.swift
1
1559
// // AttentionCell.swift // SwiftTimeMovie // // Created by DahaiZhang on 16/10/21. // Copyright © 2016年 LLQ. All rights reserved. // import UIKit class AttentionCell: UICollectionViewCell { @IBOutlet weak var movieImage: UIImageView! @IBOutlet weak var time: UILabel! @IBOutlet weak var title: UILabel! @IBOutlet weak var count: UILabel! @IBOutlet weak var director: UILabel! @IBOutlet weak var actor: UILabel! @IBOutlet weak var type: UILabel! @IBOutlet weak var button2: UIButton! @IBOutlet weak var button1: UIButton! var model: WillModel?{ didSet{ time.text = "\((model?.rMonth)!)月\((model?.rDay)!)日上映" title.text = model?.title movieImage.sd_setImage(with: URL(string: (model?.image)!)) let aStr = NSMutableAttributedString(string: "\((model?.wantedCount)!)人在期待上映") aStr.setAttributes([NSForegroundColorAttributeName:UIColor.orange], range: NSRange(location: 0, length: aStr.length-7)) count.attributedText = aStr director.text = "导演:\((model?.director)!)" actor.text = "主演:\((model?.actor1)!) \((model?.actor2)!)" type.text = model?.type } } override func awakeFromNib() { super.awakeFromNib() button2.layer.borderWidth = 2 button2.layer.borderColor = UIColor.gray.cgColor button2.layer.cornerRadius = 15 button2.clipsToBounds = true } }
apache-2.0
3bc494c9335ad3a18562008ba77ca4d2
30.102041
131
0.611549
4.209945
false
false
false
false
sunpaq/BohdiEngineDemoSwift
BEDemo/D3ViewController.swift
1
1468
// // 3DViewController.swift // BEDemo // // Created by Sun YuLi on 2017/5/22. // Copyright © 2017年 SODEC. All rights reserved. // import UIKit class D3ViewController: UIViewController { @IBOutlet weak var beview: BEView! override func viewDidLoad() { super.viewDidLoad() if let models = BEResource.shared().objModelNames as? [String] { beview.loadModelNamed(models[AppDelegate.currentIndex]) AppDelegate.currentIndex += 1 if AppDelegate.currentIndex >= models.count { AppDelegate.currentIndex = 0 } } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) //beview.renderer.setBackgroundColor(UIColor.black) beview.startDraw3DContent(BECameraRotateAroundModelManual) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) beview.stopDraw3DContent() } @IBAction func onFullscreen(_ sender: Any) { beview.frame = UIScreen.main.bounds } @IBAction func onPan(_ sender: Any) { let trans = (sender as! UIPanGestureRecognizer).translation(in: self.view) beview.renderer.rotateModel(byPanGesture: trans) } @IBAction func onPinch(_ sender: Any) { let zoom = (sender as! UIPinchGestureRecognizer).scale beview.renderer.zoomModel(byPinchGesture: zoom) } }
bsd-3-clause
0f7e2af8f79adde0cdb7d369f9319618
28.3
82
0.642321
4.373134
false
false
false
false
emadhegab/GenericDataSource
GenericDataSourceTests/ShouldShowMenuForItemTester.swift
1
2114
// // ShouldShowMenuForItemTester.swift // GenericDataSource // // Created by Mohamed Ebrahim Mohamed Afifi on 3/14/17. // Copyright © 2017 mohamede1945. All rights reserved. // import Foundation import GenericDataSource import XCTest private class _ReportBasicDataSource<CellType>: ReportBasicDataSource<CellType> where CellType: ReportCell, CellType: ReusableCell, CellType: NSObject { var result: Bool = false var indexPath: IndexPath? override func ds_collectionView(_ collectionView: GeneralCollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { self.indexPath = indexPath return result } } class ShouldShowMenuForItemTester<CellType>: DataSourceTester where CellType: ReportCell, CellType: ReusableCell, CellType: NSObject { let dataSource: ReportBasicDataSource<CellType> = _ReportBasicDataSource<CellType>() var result: Bool { return true } required init(id: Int, numberOfReports: Int, collectionView: GeneralCollectionView) { dataSource.items = Report.generate(numberOfReports: numberOfReports) dataSource.registerReusableViewsInCollectionView(collectionView) (dataSource as! _ReportBasicDataSource<CellType>).result = result } func test(indexPath: IndexPath, dataSource: AbstractDataSource, tableView: UITableView) -> Bool { return dataSource.tableView(tableView, shouldShowMenuForRowAt: indexPath) } func test(indexPath: IndexPath, dataSource: AbstractDataSource, collectionView: UICollectionView) -> Bool { return dataSource.collectionView(collectionView, shouldShowMenuForItemAt: indexPath) } func assert(result: Bool, indexPath: IndexPath, collectionView: GeneralCollectionView) { XCTAssertEqual(result, self.result) XCTAssertEqual((dataSource as! _ReportBasicDataSource<CellType>).indexPath, indexPath) } } class ShouldShowMenuForItemTester2<CellType>: ShouldShowMenuForItemTester<CellType> where CellType: ReportCell, CellType: ReusableCell, CellType: NSObject { override var result: Bool { return false } }
mit
fb757bc7a5883845bb2caae7419ecea2
37.418182
156
0.755324
5.178922
false
true
false
false
mhatzitaskos/TurnBasedSkeleton
TurnBasedTest/ListOfGamesViewController.swift
1
8107
// // ListOfGamesViewController.swift // TurnBasedTest // // Created by Markos Hatzitaskos on 350/12/15. // Copyright © 2015 Markos Hatzitaskos. All rights reserved. // import UIKit import GameKit class ListOfGamesViewController: UITableViewController { var refreshTable = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self , selector: "reloadTable", name: "kReloadMatchTable", object: nil) NSNotificationCenter.defaultCenter().addObserver(self , selector: "reloadMatches", name: "kReloadMatches", object: nil) refreshTable.addTarget(self, action: "reloadMatches", forControlEvents: UIControlEvents.ValueChanged) refreshTable.tintColor = UIColor.grayColor() refreshTable.attributedTitle = NSAttributedString(string: "LOADING", attributes: [NSForegroundColorAttributeName : UIColor.grayColor()]) refreshTable.backgroundColor = UIColor.clearColor() tableView.addSubview(refreshTable) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func reloadMatches() { GameCenterSingleton.sharedInstance.reloadMatches({ (matches: [String:[GKTurnBasedMatch]]?) in if matches != nil { print("") print("Matches loaded") } else { print("") print("There were no matches to load or some error occured") } NSNotificationCenter.defaultCenter().postNotificationName("kReloadMatchTable", object: nil) self.refreshTable.endRefreshing() }) } func reloadTable() { print("") print("Reloading list of games table") self.tableView.reloadData() } // MARK: - Table view data source override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //let cell = tableView.cellForRowAtIndexPath(indexPath) as! GameCell } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 6 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: if let inSearchingModeMatches = GameCenterSingleton.sharedInstance.matchDictionary["inSearchingModeMatches"] { return inSearchingModeMatches.count } else { return 0 } case 1: if let inInvitationModeMatches = GameCenterSingleton.sharedInstance.matchDictionary["inInvitationModeMatches"] { return inInvitationModeMatches.count } else { return 0 } case 2: if let inWaitingForIntivationReplyModeMatches = GameCenterSingleton.sharedInstance.matchDictionary["inWaitingForIntivationReplyModeMatches"] { return inWaitingForIntivationReplyModeMatches.count } else { return 0 } case 3: if let localPlayerTurnMatches = GameCenterSingleton.sharedInstance.matchDictionary["localPlayerTurnMatches"] { return localPlayerTurnMatches.count } else { return 0 } case 4: if let opponentTurnMatches = GameCenterSingleton.sharedInstance.matchDictionary["opponentTurnMatches"] { return opponentTurnMatches.count } else { return 0 } case 5: if let endedMatches = GameCenterSingleton.sharedInstance.matchDictionary["endedMatches"] { return endedMatches.count } else { return 0 } default: return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("GameCell", forIndexPath: indexPath) as! GameCell switch indexPath.section { case 0: if let inSearchingModeMatches = GameCenterSingleton.sharedInstance.matchDictionary["inSearchingModeMatches"] { cell.match = inSearchingModeMatches[indexPath.row] cell.opponentLabel.text = "Random Opponent" cell.mode = MatchMode.inSearchingModeMatches } case 1: if let inInvitationModeMatches = GameCenterSingleton.sharedInstance.matchDictionary["inInvitationModeMatches"] { cell.match = inInvitationModeMatches[indexPath.row] let opponent = GameCenterSingleton.sharedInstance.findParticipantsForMatch(cell.match!)?.opponent cell.opponentLabel.text = opponent?.player?.alias cell.mode = MatchMode.inInvitationModeMatches } case 2: if let inWaitingForIntivationReplyModeMatches = GameCenterSingleton.sharedInstance.matchDictionary["inWaitingForIntivationReplyModeMatches"] { cell.match = inWaitingForIntivationReplyModeMatches[indexPath.row] let opponent = GameCenterSingleton.sharedInstance.findParticipantsForMatch(cell.match!)?.opponent cell.opponentLabel.text = opponent?.player?.alias cell.mode = MatchMode.inWaitingForIntivationReplyModeMatches } case 3: if let localPlayerTurnMatches = GameCenterSingleton.sharedInstance.matchDictionary["localPlayerTurnMatches"] { cell.match = localPlayerTurnMatches[indexPath.row] let opponent = GameCenterSingleton.sharedInstance.findParticipantsForMatch(cell.match!)?.opponent cell.opponentLabel.text = opponent?.player?.alias cell.mode = MatchMode.localPlayerTurnMatches print("match in cell \(indexPath.section) \(indexPath.row) \(cell.match)") } case 4: if let opponentTurnMatches = GameCenterSingleton.sharedInstance.matchDictionary["opponentTurnMatches"] { cell.match = opponentTurnMatches[indexPath.row] let opponent = GameCenterSingleton.sharedInstance.findParticipantsForMatch(cell.match!)?.opponent cell.opponentLabel.text = opponent?.player?.alias cell.mode = MatchMode.opponentTurnMatches } case 5: if let endedMatches = GameCenterSingleton.sharedInstance.matchDictionary["endedMatches"] { cell.match = endedMatches[indexPath.row] let opponent = GameCenterSingleton.sharedInstance.findParticipantsForMatch(cell.match!)?.opponent cell.opponentLabel.text = opponent?.player?.alias cell.mode = MatchMode.endedMatches } default: break } cell.updateButtons() return cell } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerCell = tableView.dequeueReusableCellWithIdentifier("GameHeaderCell") as! GameHeaderCell headerCell.backgroundColor = UIColor.lightGrayColor() switch (section) { case 0: headerCell.label.text = "Searching for opponent..." case 1: headerCell.label.text = "Invited by opponent" case 2: headerCell.label.text = "Invited opponent & waiting" case 3: headerCell.label.text = "My turn" case 4: headerCell.label.text = "Opponent's turn & waiting" case 5: headerCell.label.text = "Ended matches" default: headerCell.label.text = "Other" } return headerCell } }
mit
44e7b66b31f5c550a023a22ef36ac579
39.733668
154
0.623736
5.594203
false
false
false
false
Adiel-Sharabi/Mobile-App-Performance
SwiftApp/SwiftApp/Point.swift
2
4762
// // Copyright (c) 2015 Harry Cheung // import UIKit func toRadians(value: Double) -> Double { return value * M_PI / 180.0 } func toDegrees(value: Double) -> Double { return value * 180.0 / M_PI } func == (left: Point, right: Point) -> Bool { return (left.latitudeDegrees() == right.latitudeDegrees()) && (left.longitudeDegrees() == right.longitudeDegrees()) } struct Point: Equatable { let RADIUS: Double = 6371000 var latitude: Double var longitude: Double var speed: Double var bearing: Double var hAccuracy: Double var vAccuracy: Double var timestamp: Double var lapDistance: Double var lapTime: Double var splitTime: Double var acceleration: Double var generated: Bool = false init() { self.init(latitude: 0, longitude: 0, inRadians: false) } init (latitude: Double, longitude: Double, inRadians: Bool) { if inRadians { self.latitude = latitude self.longitude = longitude } else { self.latitude = toRadians(latitude) self.longitude = toRadians(longitude) } self.speed = 0 self.bearing = 0 self.hAccuracy = 0 self.vAccuracy = 0 self.timestamp = 0 self.lapDistance = 0 self.lapTime = 0 self.splitTime = 0 self.acceleration = 0 } init (latitude: Double, longitude: Double) { self.init(latitude: latitude, longitude: longitude, inRadians: false) } init (latitude: Double, longitude: Double, bearing: Double) { self.init(latitude: latitude, longitude: longitude, inRadians: false) self.bearing = bearing } init (latitude: Double, longitude: Double, speed: Double, bearing: Double, horizontalAccuracy: Double, verticalAccuracy: Double, timestamp: Double) { self.init(latitude: latitude, longitude: longitude, inRadians: false) self.speed = speed self.bearing = bearing self.hAccuracy = horizontalAccuracy self.vAccuracy = verticalAccuracy self.timestamp = timestamp } mutating func setLapTime(startTime: Double, splitStartTime: Double) { lapTime = timestamp - startTime splitTime = timestamp - splitStartTime } func roundValue(value: Double) -> Double { return round(value * 1000000.0) / 1000000.0 } func latitudeDegrees() -> Double { return roundValue(toDegrees(latitude)) } func longitudeDegrees() -> Double { return roundValue(toDegrees(longitude)) } func subtract(point: Point) -> Point { return Point(latitude: latitude - point.latitude, longitude: longitude - point.longitude, inRadians: true) } func bearingTo(point: Point, inRadians: Bool) -> Double { let φ1 = latitude let φ2 = point.latitude let Δλ = point.longitude - longitude let y = sin(Δλ) * cos(φ2) let x = cos(φ1) * sin(φ2) - sin(φ1) * cos(φ2) * cos(Δλ) let θ = atan2(y, x) if (inRadians) { return roundValue((θ + 2 * M_PI) % M_PI) } else { return roundValue((toDegrees(θ) + 2 * 360) % 360) } } func bearingTo(point: Point) -> Double { return bearingTo(point, inRadians: false) } func destination(bearing: Double, distance: Double) -> Point { let θ = toRadians(bearing) let δ = distance / RADIUS let φ1 = latitude let λ1 = longitude let φ2 = asin(sin(φ1) * cos(δ) + cos(φ1) * sin(δ) * cos(θ)) var λ2 = λ1 + atan2(sin(θ) * sin(δ) * cos(φ1), cos(δ) - sin(φ1) * sin(φ2)) λ2 = (λ2 + 3.0 * M_PI) % (2.0 * M_PI) - M_PI // normalise to -180..+180 return Point(latitude: φ2, longitude: λ2, inRadians: true) } func distanceTo(point: Point) -> Double { let φ1 = latitude let λ1 = longitude let φ2 = point.latitude let λ2 = point.longitude let Δφ = φ2 - φ1 let Δλ = λ2 - λ1 let a = sin(Δφ / 2) * sin(Δφ / 2) + cos(φ1) * cos(φ2) * sin(Δλ / 2) * sin(Δλ / 2) return RADIUS * 2 * atan2(sqrt(a), sqrt(1 - a)) } static func intersectSimple(#p: Point, p2: Point, q: Point, q2: Point, inout intersection: Point) -> Bool { let s1_x = p2.longitude - p.longitude let s1_y = p2.latitude - p.latitude let s2_x = q2.longitude - q.longitude let s2_y = q2.latitude - q.latitude let den = (-s2_x * s1_y + s1_x * s2_y) if den == 0 { return false } let s = (-s1_y * (p.longitude - q.longitude) + s1_x * (p.latitude - q.latitude)) / den let t = ( s2_x * (p.latitude - q.latitude) - s2_y * (p.longitude - q.longitude)) / den if s >= 0 && s <= 1 && t >= 0 && t <= 1 { intersection.latitude = p.latitude + (t * s1_y) intersection.longitude = p.longitude + (t * s1_x) return true } return false } }
gpl-3.0
9298d4714cfe35e91a28d38fc6fa3797
27.325301
117
0.613356
3.253979
false
false
false
false
paulo17/Find-A-Movie-iOS
FindAMovie/NetworkOperation.swift
1
1978
import Foundation import Alamofire import SwiftyJSON enum NetworkError: ErrorType { case NetworkFailure case EmptyResult } /** * Network Operation class to perform webservice request */ class NetworkOperation { let queryURL: String typealias JSONDictionaryCompletion = ([String: AnyObject]?, ErrorType?) -> (Void) /** Initialize NetworkOperation - parameter url: URL of the web service */ init(url: String) { self.queryURL = url } /** Execute a GET request to featch data from the web - parameter completion: Callback to retour JSON Dictionnary */ func executeRequest(completionHandler: JSONDictionaryCompletion) { Alamofire .request(.GET, self.queryURL) .responseJSON { (response) in switch response.result { case .Success: guard let value = response.result.value else { return completionHandler(nil, NetworkError.EmptyResult) } let jsonDictionary = value as? [String: AnyObject] completionHandler(jsonDictionary, nil) case .Failure(let error): print(error) completionHandler(nil, NetworkError.NetworkFailure) } } } /** Get data form URL - parameter url: NSURL - parameter completion: (NSData) -> Void */ func getDataFromUrl(url: NSURL, completion: ((data: NSData?) -> Void)) { NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in if let error = error { print(error) } completion(data: data) }.resume() } }
gpl-2.0
4e3e52f6b15287130637493924c4a78d
24.371795
85
0.516684
5.800587
false
false
false
false
mengxiangyue/Swift-Design-Pattern-In-Chinese
Design_Pattern.playground/Pages/Decorator.xcplaygroundpage/Contents.swift
1
3844
/*: ### **Decorator** --- [回到列表](Index) 1. 定义:装饰模式,动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。 2. 问题:咖啡店里有最基本的咖啡,还有用基本咖啡添加不同物品新调制的咖啡。 3. 解决方案:定义基本咖啡,然后创建不同物品的装饰类,用装饰类装饰基本咖啡就获得了最终的咖啡了。 4. 使用方法: 1. 定义 Coffee 协议,明确咖啡的定义。 2. 定义具体的 Coffee (SimpleCoffee)。 3. 定义咖啡的装饰类(CoffeeDecorator),在构造的时候传入要被装饰的咖啡。 4. 定义具体的咖啡装饰类,添加新的功能。 5. 优点: 1. 对于扩展一个对象的功能,装饰模式比继承更加灵活性,不会导致类的个数急剧增加。 2. 可以通过一种动态的方式来扩展一个对象的功能,通过配置文件可以在运行时选择不同的具体装饰类,从而实现不同的行为。 3. 可以对一个对象进行多次装饰,通过使用不同的具体装饰类以及这些装饰类的排列组合,可以创造出很多不同行为的组合,得到功能更为强大的对象。 4. 具体构件类与具体装饰类可以独立变化,用户可以根据需要增加新的具体构件类和具体装饰类,原有类库代码无须改变,符合“开闭原则”。 6. 缺点: 1. 使用装饰模式进行系统设计时将产生很多小对象,这些对象的区别在于它们之间相互连接的方式有所不同,而不是它们的类或者属性值有所不同,大量小对象的产生势必会占用更多的系统资源,在一定程序上影响程序的性能。 2. 装饰模式提供了一种比继承更加灵活机动的解决方案,但同时也意味着比继承更加易于出错,排错也很困难,对于多次装饰的对象,调试时寻找错误可能需要逐级排查,较为繁琐。 */ import Foundation protocol Coffee { func getCost() -> Double func getIngredients() -> String } class SimpleCoffee: Coffee { func getCost() -> Double { return 1.0 } func getIngredients() -> String { return "Coffee" } } class CoffeeDecorator: Coffee { private let decoratedCoffee: Coffee fileprivate let ingredientSeparator: String = ", " required init(decoratedCoffee: Coffee) { self.decoratedCoffee = decoratedCoffee } func getCost() -> Double { return decoratedCoffee.getCost() } func getIngredients() -> String { return decoratedCoffee.getIngredients() } } final class Milk: CoffeeDecorator { required init(decoratedCoffee: Coffee) { super.init(decoratedCoffee: decoratedCoffee) } override func getCost() -> Double { return super.getCost() + 0.5 } override func getIngredients() -> String { return super.getIngredients() + ingredientSeparator + "Milk" } } final class WhipCoffee: CoffeeDecorator { required init(decoratedCoffee: Coffee) { super.init(decoratedCoffee: decoratedCoffee) } override func getCost() -> Double { return super.getCost() + 0.7 } override func getIngredients() -> String { return super.getIngredients() + ingredientSeparator + "Whip" } } /*: ### Usage: */ var someCoffee: Coffee = SimpleCoffee() print("Cost : \(someCoffee.getCost()); Ingredients: \(someCoffee.getIngredients())") someCoffee = Milk(decoratedCoffee: someCoffee) print("Cost : \(someCoffee.getCost()); Ingredients: \(someCoffee.getIngredients())") someCoffee = WhipCoffee(decoratedCoffee: someCoffee) print("Cost : \(someCoffee.getCost()); Ingredients: \(someCoffee.getIngredients())")
mit
ea8053dd01ebbb36c70069317b4e1016
26.747368
107
0.685888
2.828326
false
false
false
false
TonnyTao/HowSwift
how_to_update_view_in_mvvm.playground/Sources/RxSwift/Platform/Platform.Linux.swift
13
804
// // Platform.Linux.swift // Platform // // Created by Krunoslav Zaher on 12/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(Linux) import Foundation extension Thread { static func setThreadLocalStorageValue<T: AnyObject>(_ value: T?, forKey key: String) { if let newValue = value { Thread.current.threadDictionary[key] = newValue } else { Thread.current.threadDictionary[key] = nil } } static func getThreadLocalStorageValueForKey<T: AnyObject>(_ key: String) -> T? { let currentThread = Thread.current let threadDictionary = currentThread.threadDictionary return threadDictionary[key] as? T } } #endif
mit
296541b9963fa9790e05177356ee311f
24.09375
95
0.594022
4.751479
false
false
false
false
haijianhuo/TopStore
TopStore/Vendors/MIBadgeButton/HHImageCropper/HHImageScrollView.swift
1
10007
// // HHImageScrollView.swift // // Created by Haijian Huo on 8/13/17. // Copyright © 2017 Haijian Huo. All rights reserved. // import UIKit class HHImageScrollView: UIScrollView { var zoomView: UIImageView? var aspectFill: Bool = false private var imageSize: CGSize? private var pointToCenterAfterResize: CGPoint = .zero private var scaleToRestoreAfterResize: CGFloat = 0 private var sizeChanging: Bool = false required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) self.aspectFill = false self.showsVerticalScrollIndicator = false self.showsHorizontalScrollIndicator = false self.bouncesZoom = true self.scrollsToTop = false self.decelerationRate = UIScrollViewDecelerationRateFast self.delegate = self } override func didAddSubview(_ subview: UIView) { super.didAddSubview(subview) self.centerZoomView() } func setAspectFill(aspectFill: Bool) { if self.aspectFill != aspectFill { self.aspectFill = aspectFill if self.zoomView != nil { self.setMaxMinZoomScalesForCurrentBounds() if (self.zoomScale < self.minimumZoomScale) { self.zoomScale = self.minimumZoomScale } } } } override var frame: CGRect { willSet { self.sizeChanging = !newValue.size.equalTo(self.frame.size) if (self.sizeChanging) { self.prepareToResize() } } didSet { if (self.sizeChanging) { self.recoverFromResizing() } self.centerZoomView() } } // MARK: - Center zoomView within scrollView fileprivate func centerZoomView() { guard let zoomView = self.zoomView else { return } // center zoomView as it becomes smaller than the size of the screen // we need to use contentInset instead of contentOffset for better positioning when zoomView fills the screen if (self.aspectFill) { var top: CGFloat = 0 var left: CGFloat = 0 // center vertically if (self.contentSize.height < self.bounds.height) { top = (self.bounds.height - self.contentSize.height) * 0.5 } // center horizontally if (self.contentSize.width < self.bounds.width) { left = (self.bounds.width - self.contentSize.width) * 0.5 } self.contentInset = UIEdgeInsetsMake(top, left, top, left); } else { var frameToCenter = zoomView.frame // center horizontally if (frameToCenter.width < self.bounds.width) { frameToCenter.origin.x = (self.bounds.width - frameToCenter.width) * 0.5 } else { frameToCenter.origin.x = 0 } // center vertically if (frameToCenter.height < self.bounds.height) { frameToCenter.origin.y = (self.bounds.height - frameToCenter.height) * 0.5 } else { frameToCenter.origin.y = 0 } zoomView.frame = frameToCenter } } // MARK: - Configure scrollView to display new image func displayImage(image: UIImage) { // clear view for the previous image self.zoomView?.removeFromSuperview() self.zoomView = nil // reset our zoomScale to 1.0 before doing any further calculations self.zoomScale = 1.0 // make views to display the new image let zoomView = UIImageView(image: image) self.addSubview(zoomView) self.zoomView = zoomView self.configureForImageSize(imageSize: image.size) } private func configureForImageSize(imageSize: CGSize) { self.imageSize = imageSize self.contentSize = imageSize self.setMaxMinZoomScalesForCurrentBounds() self.setInitialZoomScale() self.setInitialContentOffset() self.contentInset = .zero } private func setMaxMinZoomScalesForCurrentBounds() { guard let imageSize = self.imageSize else { return } let boundsSize = self.bounds.size // calculate min/max zoomscale let xScale = boundsSize.width / imageSize.width // the scale needed to perfectly fit the image width-wise let yScale = boundsSize.height / imageSize.height // the scale needed to perfectly fit the image height-wise var minScale: CGFloat = 0 if (!self.aspectFill) { minScale = min(xScale, yScale) // use minimum of these to allow the image to become fully visible } else { minScale = max(xScale, yScale) // use maximum of these to allow the image to fill the screen } var maxScale = max(xScale, yScale) // Image must fit/fill the screen, even if its size is smaller. let xImageScale = maxScale * imageSize.width / boundsSize.width let yImageScale = maxScale * imageSize.height / boundsSize.height var maxImageScale = max(xImageScale, yImageScale) maxImageScale = max(minScale, maxImageScale) maxScale = max(maxScale, maxImageScale) // don't let minScale exceed maxScale. (If the image is smaller than the screen, we don't want to force it to be zoomed.) if (minScale > maxScale) { minScale = maxScale; } self.maximumZoomScale = maxScale self.minimumZoomScale = minScale } private func setInitialZoomScale() { guard let imageSize = self.imageSize else { return } let boundsSize = self.bounds.size let xScale = boundsSize.width / imageSize.width // the scale needed to perfectly fit the image width-wise let yScale = boundsSize.height / imageSize.height // the scale needed to perfectly fit the image height-wise let scale = max(xScale, yScale) self.zoomScale = scale } private func setInitialContentOffset() { guard let zoomView = self.zoomView else { return } let boundsSize = self.bounds.size let frameToCenter = zoomView.frame var contentOffset: CGPoint = .zero if (frameToCenter.width > boundsSize.width) { contentOffset.x = (frameToCenter.width - boundsSize.width) * 0.5 } else { contentOffset.x = 0 } if (frameToCenter.height > boundsSize.height) { contentOffset.y = (frameToCenter.height - boundsSize.height) * 0.5 } else { contentOffset.y = 0 } self.setContentOffset(contentOffset, animated: false) } // MARK: // MARK: Methods called during rotation to preserve the zoomScale and the visible portion of the image // MARK: Rotation support private func prepareToResize() { guard let zoomView = self.zoomView else { return } let boundsCenter = CGPoint(x: self.bounds.midX, y: self.bounds.midY) pointToCenterAfterResize = self.convert(boundsCenter, to: zoomView) self.scaleToRestoreAfterResize = self.zoomScale // If we're at the minimum zoom scale, preserve that by returning 0, which will be converted to the minimum // allowable scale when the scale is restored. if Float(self.scaleToRestoreAfterResize) <= Float(self.minimumZoomScale) + Float.ulpOfOne { self.scaleToRestoreAfterResize = 0 } } private func recoverFromResizing() { guard let zoomView = self.zoomView else { return } self.setMaxMinZoomScalesForCurrentBounds() // Step 1: restore zoom scale, first making sure it is within the allowable range. let maxZoomScale = max(self.minimumZoomScale, scaleToRestoreAfterResize) self.zoomScale = min(self.maximumZoomScale, maxZoomScale) // Step 2: restore center point, first making sure it is within the allowable range. // 2a: convert our desired center point back to our own coordinate space let boundsCenter = self.convert(self.pointToCenterAfterResize, from: zoomView) // 2b: calculate the content offset that would yield that center point var offset = CGPoint(x: boundsCenter.x - self.bounds.size.width / 2.0, y: boundsCenter.y - self.bounds.size.height / 2.0) // 2c: restore offset, adjusted to be within the allowable range let maxOffset = self.maximumContentOffset() let minOffset = self.minimumContentOffset() var realMaxOffset = min(maxOffset.x, offset.x) offset.x = max(minOffset.x, realMaxOffset) realMaxOffset = min(maxOffset.y, offset.y) offset.y = max(minOffset.y, realMaxOffset) self.contentOffset = offset } private func maximumContentOffset() -> CGPoint { let contentSize = self.contentSize let boundsSize = self.bounds.size return CGPoint(x: contentSize.width - boundsSize.width, y: contentSize.height - boundsSize.height) } private func minimumContentOffset() -> CGPoint { return .zero } } // MARK: UIScrollViewDelegate extension HHImageScrollView: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self.zoomView } func scrollViewDidZoom(_ scrollView: UIScrollView) { self.centerZoomView() } }
mit
2c46a5398dc863f8fbf95ad81ae18d98
33.743056
129
0.602638
5.058645
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Card/Detail/View/CardDetailEvolutionCell.swift
1
2400
// // CardDetailEvolutionCell.swift // DereGuide // // Created by zzk on 2017/6/26. // Copyright © 2017年 zzk. All rights reserved. // import UIKit class CardDetailEvolutionCell: UITableViewCell { var leftLabel: UILabel! var toIcon: CGSSCardIconView! var fromIcon: CGSSCardIconView! var arrowImageView = UIImageView(image: #imageLiteral(resourceName: "arrow-rightward").withRenderingMode(.alwaysTemplate)) weak var delegate: CGSSIconViewDelegate? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) leftLabel = UILabel() leftLabel.textColor = UIColor.black leftLabel.font = UIFont.systemFont(ofSize: 16) leftLabel.text = NSLocalizedString("进化信息", comment: "卡片详情页") contentView.addSubview(leftLabel) leftLabel.snp.makeConstraints { (make) in make.left.equalTo(10) make.top.equalTo(10) } fromIcon = CGSSCardIconView() contentView.addSubview(fromIcon) fromIcon.snp.makeConstraints { (make) in make.top.equalTo(leftLabel.snp.bottom).offset(5) make.left.equalTo(10) } contentView.addSubview(arrowImageView) arrowImageView.tintColor = .darkGray arrowImageView.snp.makeConstraints { (make) in make.left.equalTo(fromIcon.snp.right).offset(17) make.centerY.equalTo(fromIcon) } toIcon = CGSSCardIconView() contentView.addSubview(toIcon) toIcon.snp.makeConstraints { (make) in make.left.equalTo(arrowImageView.snp.right).offset(17) make.top.equalTo(fromIcon) make.bottom.equalTo(-10) } selectionStyle = .none } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension CardDetailEvolutionCell: CardDetailSetable { func setup(with card: CGSSCard) { if card.evolutionId == 0 { toIcon.cardID = card.id fromIcon.cardID = card.id - 1 fromIcon.delegate = self.delegate } else { fromIcon.cardID = card.id toIcon.cardID = card.evolutionId toIcon.delegate = self.delegate } } }
mit
387dbbb9883d114323b7f794709be995
29.896104
126
0.625053
4.531429
false
false
false
false
Chris-Perkins/Lifting-Buddy
Lifting Buddy/MessageView.swift
1
4163
// // MessageView.swift // Lifting Buddy // // Created by Christopher Perkins on 2/5/18. // Copyright © 2018 Christopher Perkins. All rights reserved. // import UIKit class MessageView: UIView { // MARK: View properties // Height that this view should be drawn as private let height: CGFloat // The message we should be displaying public let message: Message public let imageView: UIImageView public let titleLabel: UILabel // MARK: View inits init(withMessage message: Message, andHeight height: CGFloat) { imageView = UIImageView() titleLabel = UILabel() self.message = message self.height = height super.init(frame: .zero) addSubview(titleLabel) addSubview(imageView) createAndActivateTitleLabelConstraints() //createAndActivateImageViewConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("aDecoder Init Set for UIView") } // MARK: View overrides override func layoutSubviews() { super.layoutSubviews() // Title label titleLabel.setDefaultProperties() titleLabel.textColor = .white titleLabel.font = UIFont.boldSystemFont(ofSize: 18.0) titleLabel.text = message.messageTitle } // MARK: Constraints // Cling to left, top of self ; right to image view ; height of titlelabelheight private func createAndActivateTitleLabelConstraints() { titleLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: titleLabel, withCopyView: self, attribute: .left, plusConstant: 10).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: titleLabel, withCopyView: self, attribute: .top, plusConstant: statusBarHeight).isActive = true /*NSLayoutConstraint(item: imageView, attribute: .left, relatedBy: .equal, toItem: titleLabel, attribute: .right, multiplier: 1, constant: 0).isActive = true*/ NSLayoutConstraint.createViewAttributeCopyConstraint(view: titleLabel, withCopyView: self, attribute: .right).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: titleLabel, height: height - statusBarHeight).isActive = true } // Cling to right, bottom of self ; height of self ; width = height private func createAndActivateImageViewConstraints() { imageView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: imageView, withCopyView: self, attribute: .right).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: imageView, withCopyView: self, attribute: .bottom).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: imageView, height: height).isActive = true NSLayoutConstraint.createWidthConstraintForView(view: imageView, width: height).isActive = true } }
mit
c6dfe124caec4a790627f3bc91aa8b98
40.207921
107
0.515858
7.366372
false
false
false
false
onekiloparsec/SwiftAA
Tests/SwiftAATests/NumericTypeTests.swift
2
3495
// // NumericTypeTests.swift // SwiftAA // // Created by Alexander Vasenin on 03/01/2017. // Copyright © 2017 onekiloparsec. All rights reserved. // import XCTest @testable import SwiftAA class NumericTypeTests: XCTestCase { func testCircularInterval() { XCTAssertTrue(Degree(15).isWithinCircularInterval(from: 10, to: 20)) XCTAssertFalse(Degree(55).isWithinCircularInterval(from: 10, to: 20)) XCTAssertFalse(Degree(10).isWithinCircularInterval(from: 10, to: 20, isIntervalOpen: true)) XCTAssertTrue(Degree(15).isWithinCircularInterval(from: 10, to: 20, isIntervalOpen: false)) XCTAssertTrue(Degree(10).isWithinCircularInterval(from: 340, to: 20)) XCTAssertTrue(Degree(350).isWithinCircularInterval(from: 340, to: 20)) XCTAssertFalse(Degree(340).isWithinCircularInterval(from: 340, to: 20, isIntervalOpen: true)) XCTAssertTrue(Degree(340).isWithinCircularInterval(from: 340, to: 20, isIntervalOpen: false)) } func testRoundingToIncrement() { let accuracy = Second(1e-3).inJulianDays let jd = JulianDay(year: 2017, month: 1, day: 9, hour: 13, minute: 53, second: 39.87) AssertEqual(jd.rounded(toIncrement: Minute(1).inJulianDays), JulianDay(year: 2017, month: 1, day: 9, hour: 13, minute: 54), accuracy: accuracy) AssertEqual(jd.rounded(toIncrement: Minute(15).inJulianDays), JulianDay(year: 2017, month: 1, day: 9, hour: 14), accuracy: accuracy) AssertEqual(jd.rounded(toIncrement: Hour(3).inJulianDays), JulianDay(year: 2017, month: 1, day: 9, hour: 15), accuracy: accuracy) } func testConstructors() { // Damn one needs to do to increase UT coverage... AssertEqual(1.234.degrees, Degree(1.234)) AssertEqual(-1.234.degrees, Degree(-1.234)) AssertEqual(1.234.arcminutes, ArcMinute(1.234)) AssertEqual(-1.234.arcminutes, ArcMinute(-1.234)) AssertEqual(1.234.arcseconds, ArcSecond(1.234)) AssertEqual(-1.234.arcseconds, ArcSecond(-1.234)) AssertEqual(1.234.hours, Hour(1.234)) AssertEqual(-1.234.hours, Hour(-1.234)) AssertEqual(1.234.minutes, Minute(1.234)) AssertEqual(-1.234.minutes, Minute(-1.234)) AssertEqual(1.234.seconds, Second(1.234)) AssertEqual(-1.234.seconds, Second(-1.234)) AssertEqual(1.234.radians, Radian(1.234)) AssertEqual(-1.234.radians, Radian(-1.234)) AssertEqual(1.234.days, Day(1.234)) AssertEqual(-1.234.days, Day(-1.234)) AssertEqual(1.234.julianDays, JulianDay(1.234)) AssertEqual(-1.234.julianDays, JulianDay(-1.234)) let s1 = 1.234.sexagesimal XCTAssertEqual(s1.sign, .plus) XCTAssertEqual(s1.radical, 1) XCTAssertEqual(s1.minute, 14) XCTAssertEqual(s1.second, 2.4, accuracy: 0.000000001) // rounding error... XCTAssertEqual(1.234.sexagesimalShortString, "+01:14:02.4") // One needs a true sexagesimal library... // let s2 = -1.234.sexagesimal // let s3 = -0.123.sexagesimal // XCTAssertEqual(s2.sign, .minus) // XCTAssertEqual(s2.radical, -1) // XCTAssertEqual(s2.minute, 2) // XCTAssertEqual(s2.second, 3.4) // // XCTAssertEqual(s3.sign, .minus) // XCTAssertEqual(s3.radical, 0) // XCTAssertEqual(s3.minute, 1) // XCTAssertEqual(s3.second, 2.3) // XCTAssertEqual(-1.234.sexagesimalShortString, "") } }
mit
d9e507208d6e6af64f188590c6cfecf2
38.704545
151
0.65312
3.554425
false
true
false
false
liuchuo/Swift-practice
20150626-1.playground/Contents.swift
1
883
//: Playground - noun: a place where people can play import UIKit //元组类型的访问级别,遵循元组中字段最低级的访问级别 private class Employee { var no : Int = 0 var name : String = "" var job : String? var salary : Double = 0 var dept : Department? } struct Department { var no : Int = 0 var name : String = "" } private let emp = Employee() var dept = Department() private var student1 = (dept,emp) //因为字段dept和emp的最低访问级别是private 所以student1访问级别也是private 符合统一性原则 //枚举类型的访问级别继承自该枚举,因此我们不能为枚举中的成员指定访问级别 public enum WeekDays { case Monday case Tuesday case Wednsday case Thursday case Friday } //由于WeekDays枚举类型是public访问级别,因而它的成员也是public级别
gpl-2.0
0cae0b6e8ef0e3a199192bcdcc0722d9
19.121212
61
0.702866
3.0553
false
false
false
false
blinksh/blink
Blink/SmarterKeys/SmarterTermInput.swift
1
15610
////////////////////////////////////////////////////////////////////////////////// // // B L I N K // // Copyright (C) 2016-2019 Blink Mobile Shell Project // // This file is part of Blink. // // Blink 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. // // Blink 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 Blink. If not, see <http://www.gnu.org/licenses/>. // // In addition, Blink is also subject to certain additional terms under // GNU GPL version 3 section 7. // // You should have received a copy of these additional terms immediately // following the terms and conditions of the GNU General Public License // which accompanied the Blink Source Code. If not, see // <http://www.github.com/blinksh/blink>. // //////////////////////////////////////////////////////////////////////////////// import UIKit import Combine class CaretHider { var _cancelable: AnyCancellable? = nil init(view: UIView) { _cancelable = view.layer.publisher(for: \.sublayers).sink { (layers) in if let caretView = view.value(forKeyPath: "caretView") as? UIView { caretView.isHidden = true } if let floatingView = view.value(forKeyPath: "floatingCaretView") as? UIView { floatingView.isHidden = true } } } } @objc class SmarterTermInput: KBWebView { var kbView = KBView() lazy var _kbProxy: KBProxy = { KBProxy(kbView: self.kbView) }() private var _inputAccessoryView: UIView? = nil var isHardwareKB: Bool { kbView.traits.isHKBAttached } weak var device: TermDevice? = nil { didSet { reportStateReset() } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect, configuration: WKWebViewConfiguration) { super.init(frame: frame, configuration: configuration) kbView.keyInput = self kbView.lang = textInputMode?.primaryLanguage ?? "" // Assume hardware kb by default, since sometimes we don't have kbframe change events // if shortcuts toggle in Settings.app is off. kbView.traits.isHKBAttached = true if traitCollection.userInterfaceIdiom == .pad { _setupAssistantItem() } else { _setupAccessoryView() } KBSound.isMutted = BKUserConfigurationManager.userSettingsValue(forKey: BKUserConfigMuteSmartKeysPlaySound) } override func layoutSubviews() { super.layoutSubviews() kbView.setNeedsLayout() } func shouldUseWKCopyAndPaste() -> Bool { false } private var _caretHider: CaretHider? = nil override func ready() { super.ready() reportLang() // device?.focus() kbView.isHidden = false kbView.invalidateIntrinsicContentSize() // _refreshInputViews() if let v = selectionView() { _caretHider = CaretHider(view: v) } } func reset() { } func reportLang() { let lang = self.textInputMode?.primaryLanguage ?? "" kbView.lang = lang reportLang(lang, isHardwareKB: kbView.traits.isHKBAttached) } override var inputAssistantItem: UITextInputAssistantItem { let item = super.inputAssistantItem if item.trailingBarButtonGroups.count > 1 { item.trailingBarButtonGroups = [item.trailingBarButtonGroups[0]] } if item.trailingBarButtonGroups.count > 0 { item.leadingBarButtonGroups = [] } kbView.setNeedsLayout() return item } override func becomeFirstResponder() -> Bool { sync(traits: KBTracker.shared.kbTraits, device: KBTracker.shared.kbDevice, hideSmartKeysWithHKB: KBTracker.shared.hideSmartKeysWithHKB) let res = super.becomeFirstResponder() if !webViewReady { return res } device?.focus() kbView.isHidden = false setNeedsLayout() _refreshInputViews() _inputAccessoryView?.isHidden = false return res } var isRealFirstResponder: Bool { contentView()?.isFirstResponder == true } func reportStateReset() { reportStateReset(false) device?.view?.cleanSelection() } func reportStateWithSelection() { reportStateReset(device?.view?.hasSelection ?? false) } func _refreshInputViews() { guard traitCollection.userInterfaceIdiom == .pad, let assistantItem = contentView()?.inputAssistantItem else { if (KBTracker.shared.hideSmartKeysWithHKB && kbView.traits.isHKBAttached) { _removeSmartKeys() } contentView()?.reloadInputViews() kbView.reset() // _inputAccessoryView?.invalidateIntrinsicContentSize() reportStateReset() return; } assistantItem.leadingBarButtonGroups = [.init(barButtonItems: [UIBarButtonItem()], representativeItem: nil)] contentView()?.reloadInputViews() if (KBTracker.shared.hideSmartKeysWithHKB && kbView.traits.isHKBAttached) { _removeSmartKeys() } contentView()?.reloadInputViews() kbView.reset() reportStateReset() // Double reload inputs fixes: https://github.com/blinksh/blink/issues/803 contentView()?.reloadInputViews() kbView.isHidden = false } override func resignFirstResponder() -> Bool { let res = super.resignFirstResponder() if res { device?.blur() kbView.isHidden = true _inputAccessoryView?.isHidden = true reloadInputViews() } return res } func _setupAccessoryView() { inputAssistantItem.leadingBarButtonGroups = [] inputAssistantItem.trailingBarButtonGroups = [] if let _ = _inputAccessoryView as? KBAccessoryView { } else { _inputAccessoryView = KBAccessoryView(kbView: kbView) } } override var inputAccessoryView: UIView? { _inputAccessoryView } func sync(traits: KBTraits, device: KBDevice, hideSmartKeysWithHKB: Bool) { kbView.kbDevice = device var needToReload = false defer { kbView.traits = traits if let scene = window?.windowScene { if traitCollection.userInterfaceIdiom == .phone { kbView.traits.isPortrait = scene.interfaceOrientation.isPortrait } else if kbView.traits.isFloatingKB { kbView.traits.isPortrait = true } else { kbView.traits.isPortrait = scene.interfaceOrientation.isPortrait } } if needToReload { DispatchQueue.main.async { self._refreshInputViews() } } } if hideSmartKeysWithHKB && traits.isHKBAttached { _removeSmartKeys() return } if traits.isFloatingKB { _setupAccessoryView() return } if traitCollection.userInterfaceIdiom == .pad { needToReload = inputAssistantItem.trailingBarButtonGroups.count != 1 _setupAssistantItem() } else { needToReload = (_inputAccessoryView as? KBAccessoryView) == nil _setupAccessoryView() } } func _setupAssistantItem() { let item = inputAssistantItem let proxyItem = UIBarButtonItem(customView: _kbProxy) let group = UIBarButtonItemGroup(barButtonItems: [proxyItem], representativeItem: nil) item.leadingBarButtonGroups = [] item.trailingBarButtonGroups = [group] } func _removeSmartKeys() { _inputAccessoryView = UIView(frame: .zero) guard let item = contentView()?.inputAssistantItem else { return } item.leadingBarButtonGroups = [] item.trailingBarButtonGroups = [] setNeedsLayout() } override func _keyboardDidChangeFrame(_ notification: Notification) { } override func _keyboardWillChangeFrame(_ notification: Notification) { } override func _keyboardWillShow(_ notification: Notification) { } override func _keyboardWillHide(_ notification: Notification) { } override func _keyboardDidHide(_ notification: Notification) { } override func _keyboardDidShow(_ notification: Notification) { } } // - MARK: Web communication extension SmarterTermInput { override func onOut(_ data: String) { defer { kbView.turnOffUntracked() } guard let device = device, let deviceView = device.view, let scene = deviceView.window?.windowScene, scene.activationState == .foregroundActive else { return } deviceView.displayInput(data) let ctrlC = "\u{0003}" let ctrlD = "\u{0004}" if data == ctrlC || data == ctrlD, device.delegate?.handleControl(data) == true { return } device.write(data) } override func onCommand(_ command: String) { kbView.turnOffUntracked() guard let device = device, let scene = device.view.window?.windowScene, scene.activationState == .foregroundActive, let cmd = Command(rawValue: command), let spCtrl = spaceController else { return } spCtrl._onCommand(cmd) } var spaceController: SpaceController? { var n = next while let responder = n { if let spCtrl = responder as? SpaceController { return spCtrl } n = responder.next } return nil } override func onSelection(_ args: [AnyHashable : Any]) { if let dir = args["dir"] as? String, let gran = args["gran"] as? String { device?.view?.modifySelection(inDirection: dir, granularity: gran) } else if let op = args["command"] as? String { switch op { case "change": device?.view?.modifySideOfSelection() case "copy": copy(self) case "paste": device?.view?.pasteSelection(self) case "cancel": fallthrough default: device?.view?.cleanSelection() } } } override func onMods() { kbView.stopRepeats() } override func onIME(_ event: String, data: String) { if event == "compositionstart" && data.isEmpty { } else if event == "compositionend" { kbView.traits.isIME = false } else { // "compositionupdate" kbView.traits.isIME = true } } func stuckKey() -> KeyCode? { let mods: UIKeyModifierFlags = [.shift, .control, .alternate, .command] let stuck = mods.intersection(trackingModifierFlags) // Return command key first if stuck.contains(.command) { return KeyCode.commandLeft } if stuck.contains(.shift) { return KeyCode.shiftLeft } if stuck.contains(.control) { return KeyCode.controlLeft } if stuck.contains(.alternate) { return KeyCode.optionLeft } return nil } } // - MARK: Config extension SmarterTermInput { @objc private func _updateSettings() { // KBSound.isMutted = BKUserConfigurationManager.userSettingsValue(forKey: BKUserConfigMuteSmartKeysPlaySound) // let hideSmartKeysWithHKB = !BKUserConfigurationManager.userSettingsValue(forKey: BKUserConfigShowSmartKeysWithXKeyBoard) // // if hideSmartKeysWithHKB != hideSmartKeysWithHKB { // _hideSmartKeysWithHKB = hideSmartKeysWithHKB // if traitCollection.userInterfaceIdiom == .pad { // _setupAssistantItem() // } else { // _setupAccessoryView() // } // _refreshInputViews() // } } } // - MARK: Commands extension SmarterTermInput { override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { switch action { case #selector(UIResponder.paste(_:)): // do not touch UIPasteboard before actual paste to skip exta notification. return true// UIPasteboard.general.string != nil case #selector(UIResponder.copy(_:)), #selector(UIResponder.cut(_:)): // When the action is requested from the keyboard, the sender will be nil. // In that case we let it go through to the WKWebView. // Otherwise, we check if there is a selection. return (sender == nil) || (sender != nil && device?.view?.hasSelection == true) case #selector(TermView.pasteSelection(_:)), #selector(Self.soSelection(_:)), #selector(Self.googleSelection(_:)), #selector(Self.shareSelection(_:)): return sender != nil && device?.view?.hasSelection == true case #selector(Self.copyLink(_:)), #selector(Self.openLink(_:)): return sender != nil && device?.view?.detectedLink != nil default: // if #available(iOS 15.0, *) { // switch action { // case #selector(UIResponder.pasteAndMatchStyle(_:)), // #selector(UIResponder.pasteAndSearch(_:)), // #selector(UIResponder.pasteAndGo(_:)): return false // case _: break // } // } return super.canPerformAction(action, withSender: sender) } } override func copy(_ sender: Any?) { if shouldUseWKCopyAndPaste() { super.copy(sender) } else { device?.view?.copy(sender) } } override func paste(_ sender: Any?) { if shouldUseWKCopyAndPaste() { super.paste(sender) } else { device?.view?.paste(sender) } } @objc func copyLink(_ sender: Any) { guard let deviceView = device?.view, let url = deviceView.detectedLink else { return } UIPasteboard.general.url = url deviceView.cleanSelection() } @objc func openLink(_ sender: Any) { guard let deviceView = device?.view, let url = deviceView.detectedLink else { return } deviceView.cleanSelection() blink_openurl(url) } @objc func pasteSelection(_ sender: Any) { device?.view?.pasteSelection(sender) } @objc func googleSelection(_ sender: Any) { guard let deviceView = device?.view, let query = deviceView.selectedText?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed), let url = URL(string: "https://google.com/search?q=\(query)") else { return } blink_openurl(url) } @objc func soSelection(_ sender: Any) { guard let deviceView = device?.view, let query = deviceView.selectedText?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed), let url = URL(string: "https://stackoverflow.com/search?q=\(query)") else { return } blink_openurl(url) } @objc func shareSelection(_ sender: Any) { guard let vc = device?.delegate?.viewController(), let deviceView = device?.view, let text = deviceView.selectedText else { return } let ctrl = UIActivityViewController(activityItems: [text], applicationActivities: nil) ctrl.popoverPresentationController?.sourceView = deviceView ctrl.popoverPresentationController?.sourceRect = deviceView.selectionRect vc.present(ctrl, animated: true, completion: nil) } } extension SmarterTermInput: TermInput { var secureTextEntry: Bool { get { false } set(secureTextEntry) { } } } class VSCodeInput: SmarterTermInput { override func shouldUseWKCopyAndPaste() -> Bool { true } override func canBeFocused() -> Bool { let res = super.canBeFocused() if res == false { return KBTracker.shared.input == self } return res } }
gpl-3.0
b212facd7a9dbd2aa6f0946b78df19c9
25.729452
139
0.641576
4.43718
false
false
false
false
practicalswift/swift
validation-test/compiler_crashers_fixed/00118-swift-dependentgenerictyperesolver-resolvegenerictypeparamtype.swift
65
1225
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func v<ih>() -> (ih, ih -> ih) -> ih { h ih h.b = { } { ih) { ed } } protocol v { } class h: v{ class func b {} class m<n : m> { } func u(l: Any, kj: Any) -> (((Any, Any) -> Any) -> Any) { l { } } func l(lk: (((Any, Any) -> Any) -> Any)) -> Any { l lk({ }) } func dc(a: v) -> <n>(() -> n) -> v { } class m: m { } class f : x { } protocol m { } k f : m { } k x<g, q: m where g.x == q> { } class ji<n>: u { q(fe: n) { } } protocol m { } k w<gf> : m { func l(l: w.r) { } } func ^(u: kj, l) -> l { } protocol u { } protocol l : u { } protocol w : u { } protocol h { } k h : h { } func b<ih : l, l : h where l.v == ih> (l: l) { } func b<f : h where f.v == w> (l: f) { } k m<n> { } class u<v : l, ih : l where v.h == ih> { } protocol l { } k w<ed : l> : l { } protocol w : l { func l
apache-2.0
4ae98a37814ea7efa79ac53b15a55cc8
15.333333
79
0.52
2.45491
false
false
false
false
RogueAndy/RogueKit2
RogueKitDemo/RogueKitDemo/Carthage/Checkouts/SnapKit/Example-iOS/demos/SimpleLayoutViewController.swift
3
2634
// // SimpleLayoutViewController.swift // SnapKit // // Created by Spiros Gerokostas on 01/03/16. // Copyright © 2016 SnapKit Team. All rights reserved. // import UIKit class SimpleLayoutViewController: UIViewController { var didSetupConstraints = false let blackView: UIView = { let view = UIView() view.backgroundColor = .blackColor() return view }() let redView: UIView = { let view = UIView() view.backgroundColor = .redColor() return view }() let yellowView: UIView = { let view = UIView() view.backgroundColor = .yellowColor() return view }() let blueView: UIView = { let view = UIView() view.backgroundColor = .blueColor() return view }() let greenView: UIView = { let view = UIView() view.backgroundColor = .greenColor() return view }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() view.addSubview(blackView) view.addSubview(redView) view.addSubview(yellowView) view.addSubview(blueView) view.addSubview(greenView) view.setNeedsUpdateConstraints() } override func updateViewConstraints() { if (!didSetupConstraints) { blackView.snp_makeConstraints { make in make.center.equalTo(view) make.size.equalTo(CGSizeMake(100.0, 100.0)) } redView.snp_makeConstraints { make in make.top.equalTo(blackView.snp_bottom).offset(20.0) make.left.equalTo(20.0) make.size.equalTo(CGSizeMake(100.0, 100.0)) } yellowView.snp_makeConstraints { make in make.top.equalTo(blackView.snp_bottom).offset(20.0) make.left.equalTo(blackView.snp_right).offset(20.0) make.size.equalTo(CGSizeMake(100.0, 100.0)) } blueView.snp_makeConstraints { make in make.bottom.equalTo(blackView.snp_top).offset(-20.0) make.left.equalTo(blackView.snp_right).offset(20.0) make.size.equalTo(CGSizeMake(100.0, 100.0)) } greenView.snp_makeConstraints { make in make.bottom.equalTo(blackView.snp_top).offset(-20.0) make.right.equalTo(blackView.snp_left).offset(-20.0) make.size.equalTo(CGSizeMake(100.0, 100.0)) } didSetupConstraints = true } super.updateViewConstraints() } }
mit
541394706753c6e2b1409f70c90204e4
25.867347
68
0.576149
4.48552
false
false
false
false
Conche/Conche
Conche/Source.swift
2
1713
import Darwin import PathKit public protocol SourceType { func search(dependency:Dependency) -> [Specification] func update() throws } public class LocalFilesystemSource : SourceType { let path: Path public init(path: Path) { self.path = path } public func search(dependency:Dependency) -> [Specification] { let filename = "\(dependency.name).podspec.json" let paths = try? path.children().filter { $0.description.hasSuffix(filename) } ?? [] let specs = paths!.flatMap { (file:Path) in try? Specification(path:file) } return specs.filter { dependency.satisfies($0.version) } } public func update() throws {} } public class GitFilesystemSource : SourceType { let name:String let uri:String public init(name:String, uri:String) { self.name = name self.uri = uri } // TODO, silent error handling public func search(dependency:Dependency) -> [Specification] { let children = try? (path + "Specs" + dependency.name).children() let podspecs = (children ?? []).map { path in return path + "\(dependency.name).podspec.json" } return podspecs.flatMap(loadFile).filter { dependency.satisfies($0.version) } } func loadFile(path:Path) -> Specification? { do { return try Specification(path: path) } catch { print("\(path): \(error)") return nil } } var path:Path { return Path("~/.conche/sources/\(name)").normalize() } public func update() throws { let destination = path if destination.exists { try path.chdir { try invoke("git", ["pull", uri, "master"]) } } else { try invoke("git", ["clone", "--depth", "1", uri, path.description]) } } }
bsd-2-clause
fc23e92c081cc185e50c52c984bc9bfd
23.126761
88
0.638062
3.928899
false
false
false
false
JaSpa/swift
test/stmt/statements.swift
4
13788
// RUN: %target-typecheck-verify-swift /* block comments */ /* /* nested too */ */ func markUsed<T>(_ t: T) {} func f1(_ a: Int, _ y: Int) {} func f2() {} func f3() -> Int {} func invalid_semi() { ; // expected-error {{';' statements are not allowed}} {{3-5=}} } func nested1(_ x: Int) { var y : Int func nested2(_ z: Int) -> Int { return x+y+z } _ = nested2(1) } func funcdecl5(_ a: Int, y: Int) { var x : Int // a few statements if (x != 0) { if (x != 0 || f3() != 0) { // while with and without a space after it. while(true) { 4; 2; 1 } // expected-warning 3 {{integer literal is unused}} while (true) { 4; 2; 1 } // expected-warning 3 {{integer literal is unused}} } } // Assignment statement. x = y (x) = y 1 = x // expected-error {{cannot assign to a literal value}} (1) = x // expected-error {{cannot assign to a literal value}} (x:1).x = 1 // expected-error {{cannot assign to immutable expression of type 'Int'}} var tup : (x:Int, y:Int) tup.x = 1 _ = tup let B : Bool // if/then/else. if (B) { } else if (y == 2) { } // This diagnostic is terrible - rdar://12939553 if x {} // expected-error {{'Int' is not convertible to 'Bool'}} if true { if (B) { } else { } } if (B) { f1(1,2) } else { f2() } if (B) { if (B) { f1(1,2) } else { f2() } } else { f2() } // while statement. while (B) { } // It's okay to leave out the spaces in these. while(B) {} if(B) {} } struct infloopbool { var boolValue: infloopbool { return self } } func infloopbooltest() { if (infloopbool()) {} // expected-error {{'infloopbool' is not convertible to 'Bool'}} } // test "builder" API style extension Int { static func builder() -> Int { } var builderProp: Int { return 0 } func builder2() {} } Int .builder() .builderProp .builder2() struct SomeGeneric<T> { static func builder() -> SomeGeneric<T> { } var builderProp: SomeGeneric<T> { return .builder() } func builder2() {} } SomeGeneric<Int> .builder() .builderProp .builder2() break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}} continue // expected-error {{'continue' is only allowed inside a loop}} while true { func f() { break // expected-error {{'break' is only allowed inside a loop}} continue // expected-error {{'continue' is only allowed inside a loop}} } // Labeled if MyIf: if 1 != 2 { break MyIf continue MyIf // expected-error {{'continue' cannot be used with if statements}} break // break the while continue // continue the while. } } // Labeled if MyOtherIf: if 1 != 2 { break MyOtherIf continue MyOtherIf // expected-error {{'continue' cannot be used with if statements}} break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if}} continue // expected-error {{'continue' is only allowed inside a loop}} } do { break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}} } func tuple_assign() { var a,b,c,d : Int (a,b) = (1,2) func f() -> (Int,Int) { return (1,2) } ((a,b), (c,d)) = (f(), f()) } func missing_semicolons() { var w = 321 func g() {} g() w += 1 // expected-error{{consecutive statements}} {{6-6=;}} var z = w"hello" // expected-error{{consecutive statements}} {{12-12=;}} expected-warning {{string literal is unused}} class C {}class C2 {} // expected-error{{consecutive statements}} {{14-14=;}} struct S {}struct S2 {} // expected-error{{consecutive statements}} {{14-14=;}} func j() {}func k() {} // expected-error{{consecutive statements}} {{14-14=;}} } //===--- Return statement. return 42 // expected-error {{return invalid outside of a func}} return // expected-error {{return invalid outside of a func}} func NonVoidReturn1() -> Int { return // expected-error {{non-void function should return a value}} } func NonVoidReturn2() -> Int { return + // expected-error {{unary operator cannot be separated from its operand}} {{11-1=}} expected-error {{expected expression in 'return' statement}} } func VoidReturn1() { if true { return } // Semicolon should be accepted -- rdar://11344875 return; // no-error } func VoidReturn2() { return () // no-error } func VoidReturn3() { return VoidReturn2() // no-error } //===--- If statement. func IfStmt1() { if 1 > 0 // expected-error {{expected '{' after 'if' condition}} _ = 42 } func IfStmt2() { if 1 > 0 { } else // expected-error {{expected '{' after 'else'}} _ = 42 } //===--- While statement. func WhileStmt1() { while 1 > 0 // expected-error {{expected '{' after 'while' condition}} _ = 42 } //===-- Do statement. func DoStmt() { // This is just a 'do' statement now. do { } } func DoWhileStmt() { do { // expected-error {{'do-while' statement is not allowed; use 'repeat-while' instead}} {{3-5=repeat}} } while true } //===--- Repeat-while statement. func RepeatWhileStmt1() { repeat {} while true repeat {} while false repeat { break } while true repeat { continue } while true } func RepeatWhileStmt2() { repeat // expected-error {{expected '{' after 'repeat'}} expected-error {{expected 'while' after body of 'repeat' statement}} } func RepeatWhileStmt4() { repeat { } while + // expected-error {{unary operator cannot be separated from its operand}} {{12-1=}} expected-error {{expected expression in 'repeat-while' condition}} } func brokenSwitch(_ x: Int) -> Int { switch x { case .Blah(var rep): // expected-error{{enum case 'Blah' not found in type 'Int'}} return rep } } func switchWithVarsNotMatchingTypes(_ x: Int, y: Int, z: String) -> Int { switch (x,y,z) { case (let a, 0, _), (0, let a, _): // OK return a case (let a, _, _), (_, _, let a): // expected-error {{pattern variable bound to type 'String', expected type 'Int'}} return a } } func breakContinue(_ x : Int) -> Int { Outer: for _ in 0...1000 { Switch: switch x { case 42: break Outer case 97: continue Outer case 102: break Switch case 13: continue case 139: break // <rdar://problem/16563853> 'break' should be able to break out of switch statements } } // <rdar://problem/16692437> shadowing loop labels should be an error Loop: // expected-note {{previously declared here}} for _ in 0...2 { Loop: // expected-error {{label 'Loop' cannot be reused on an inner statement}} for _ in 0...2 { } } // <rdar://problem/16798323> Following a 'break' statement by another statement on a new line result in an error/fit-it switch 5 { case 5: markUsed("before the break") break markUsed("after the break") // 'markUsed' is not a label for the break. default: markUsed("") } let x : Int? = 42 // <rdar://problem/16879701> Should be able to pattern match 'nil' against optionals switch x { case .some(42): break case nil: break } } enum MyEnumWithCaseLabels { case Case(one: String, two: Int) } func testMyEnumWithCaseLabels(_ a : MyEnumWithCaseLabels) { // <rdar://problem/20135489> Enum case labels are ignored in "case let" statements switch a { case let .Case(one: _, two: x): break // ok case let .Case(xxx: _, two: x): break // expected-error {{tuple pattern element label 'xxx' must be 'one'}} // TODO: In principle, reordering like this could be supported. case let .Case(two: _, one: x): break // expected-error {{tuple pattern element label}} } } // "defer" func test_defer(_ a : Int) { defer { VoidReturn1() } defer { breakContinue(1)+42 } // expected-warning {{result of operator '+' is unused}} // Ok: defer { while false { break } } // Not ok. while false { defer { break } } // expected-error {{'break' cannot transfer control out of a defer statement}} defer { return } // expected-error {{'return' cannot transfer control out of a defer statement}} } class SomeTestClass { var x = 42 func method() { defer { x = 97 } // self. not required here! } } class SomeDerivedClass: SomeTestClass { override init() { defer { super.init() // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}} } } } func test_guard(_ x : Int, y : Int??, cond : Bool) { // These are all ok. guard let a = y else {} markUsed(a) guard let b = y, cond else {} guard case let c = x, cond else {} guard case let Optional.some(d) = y else {} guard x != 4, case _ = x else { } guard let e, cond else {} // expected-error {{variable binding in a condition requires an initializer}} guard case let f? : Int?, cond else {} // expected-error {{variable binding in a condition requires an initializer}} guard let g = y else { markUsed(g) // expected-error {{variable declared in 'guard' condition is not usable in its body}} } guard let h = y, cond {} // expected-error {{expected 'else' after 'guard' condition}} guard case _ = x else {} // expected-warning {{'guard' condition is always true, body is unreachable}} } func test_is_as_patterns() { switch 4 { case is Int: break // expected-warning {{'is' test is always true}} case _ as Int: break // expected-warning {{'as' test is always true}} case _: break } } // <rdar://problem/21387308> Fuzzing SourceKit: crash in Parser::parseStmtForEach(...) func matching_pattern_recursion() { switch 42 { case { // expected-error {{expression pattern of type '() -> ()' cannot match values of type 'Int'}} for i in zs { } }: break } } // <rdar://problem/18776073> Swift's break operator in switch should be indicated in errors func r18776073(_ a : Int?) { switch a { case nil: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{14-14= break}} case _?: break } } // <rdar://problem/22491782> unhelpful error message from "throw nil" func testThrowNil() throws { throw nil // expected-error {{cannot infer concrete Error for thrown 'nil' value}} } // rdar://problem/23684220 // Even if the condition fails to typecheck, save it in the AST anyway; the old // condition may have contained a SequenceExpr. func r23684220(_ b: Any) { if let _ = b ?? b {} // expected-error {{initializer for conditional binding must have Optional type, not 'Any'}} } // <rdar://problem/21080671> QoI: try/catch (instead of do/catch) creates silly diagnostics func f21080671() { try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}} } catch { } try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}} f21080671() } catch let x as Int { } catch { } } // <rdar://problem/24467411> QoI: Using "&& #available" should fixit to comma // https://twitter.com/radexp/status/694561060230184960 func f(_ x : Int, y : Int) { if x == y && #available(iOS 52, *) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}} if #available(iOS 52, *) && x == y {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{27-30=,}} // https://twitter.com/radexp/status/694790631881883648 if x == y && let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}} if x == y&&let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-14=,}} } // <rdar://problem/25178926> QoI: Warn about cases where switch statement "ignores" where clause enum Type { case Foo case Bar } func r25178926(_ a : Type) { switch a { case .Foo, .Bar where 1 != 100: // expected-warning @-1 {{'where' only applies to the second pattern match in this case}} // expected-note @-2 {{disambiguate by adding a line break between them if this is desired}} {{14-14=\n }} // expected-note @-3 {{duplicate the 'where' on both patterns to check both patterns}} {{12-12= where 1 != 100}} break } switch a { case .Foo: break case .Bar where 1 != 100: break } switch a { case .Foo, // no warn .Bar where 1 != 100: break } switch a { case .Foo where 1 != 100, .Bar where 1 != 100: break } } do { guard 1 == 2 else { break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}} } } func fn(a: Int) { guard a < 1 else { break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}} } } func fn(x: Int) { if x >= 0 { guard x < 1 else { guard x < 2 else { break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}} } return } } } func bad_if() { if 1 {} // expected-error {{'Int' is not convertible to 'Bool'}} if (x: false) {} // expected-error {{'(x: Bool)' is not convertible to 'Bool'}} if (x: 1) {} // expected-error {{'(x: Int)' is not convertible to 'Bool'}} } // Errors in case syntax class case, // expected-error {{expected identifier in enum 'case' declaration}} expected-error {{expected pattern}} case // expected-error {{expected identifier after comma in enum 'case' declaration}} expected-error {{expected identifier in enum 'case' declaration}} expected-error {{enum 'case' is not allowed outside of an enum}} expected-error {{expected pattern}} // NOTE: EOF is important here to properly test a code path that used to crash the parser
apache-2.0
c3797c5cc8a684ad92ee01b2b31360d3
25.982387
253
0.62199
3.517347
false
false
false
false
yotao/YunkuSwiftSDKTEST
YunkuSwiftSDK/YunkuSwiftSDK/Class/Data/OauthData.swift
1
883
// // Created by Brandon on 15/6/1. // Copyright (c) 2015 goukuai. All rights reserved. // import Foundation class OauthData: BaseData { static let keyAccessToken = "access_token" static let keyExpiresIn = "expires_in" static let keyError = "error" var accessToken: String = "" var expiresIn: Int = 0 class func create(_ dic: NSDictionary) -> OauthData { let data = OauthData() data.code = (dic[ReturnResult.keyCode] as? Int)! var returnResult = dic[ReturnResult.keyResult] as? Dictionary<String, AnyObject>; if data.code == HTTPStatusCode.ok.rawValue { data.accessToken = (returnResult?[keyAccessToken] as? String)! data.expiresIn = (returnResult?[keyExpiresIn] as? Int)! } else { data.errorMsg = (returnResult?[keyError] as? String)! } return data } }
mit
b3a7219772dd87d7b45663aaaa46f4ee
29.448276
89
0.628539
3.959641
false
false
false
false
coach-plus/ios
Pods/RxSwift/RxSwift/Observables/Map.swift
6
2544
// // Map.swift // RxSwift // // Created by Krunoslav Zaher on 3/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Projects each element of an observable sequence into a new form. - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) - parameter transform: A transform function to apply to each source element. - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. */ public func map<Result>(_ transform: @escaping (Element) throws -> Result) -> Observable<Result> { return Map(source: self.asObservable(), transform: transform) } } final private class MapSink<SourceType, Observer: ObserverType>: Sink<Observer>, ObserverType { typealias Transform = (SourceType) throws -> ResultType typealias ResultType = Observer.Element typealias Element = SourceType private let _transform: Transform init(transform: @escaping Transform, observer: Observer, cancel: Cancelable) { self._transform = transform super.init(observer: observer, cancel: cancel) } func on(_ event: Event<SourceType>) { switch event { case .next(let element): do { let mappedElement = try self._transform(element) self.forwardOn(.next(mappedElement)) } catch let e { self.forwardOn(.error(e)) self.dispose() } case .error(let error): self.forwardOn(.error(error)) self.dispose() case .completed: self.forwardOn(.completed) self.dispose() } } } final private class Map<SourceType, ResultType>: Producer<ResultType> { typealias Transform = (SourceType) throws -> ResultType private let _source: Observable<SourceType> private let _transform: Transform init(source: Observable<SourceType>, transform: @escaping Transform) { self._source = source self._transform = transform } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { let sink = MapSink(transform: self._transform, observer: observer, cancel: cancel) let subscription = self._source.subscribe(sink) return (sink: sink, subscription: subscription) } }
mit
7c0cd1af946ca90c587b0a3077ef67fc
32.025974
174
0.649233
4.789077
false
false
false
false
neilpa/Rex
Source/UIKit/UILabel.swift
2
1057
// // UILabel.swift // Rex // // Created by Neil Pankey on 6/19/15. // Copyright (c) 2015 Neil Pankey. All rights reserved. // import ReactiveCocoa import UIKit extension UILabel { /// Wraps a label's `text` value in a bindable property. public var rex_text: MutableProperty<String?> { return associatedProperty(self, key: &textKey, initial: { $0.text }, setter: { $0.text = $1 }) } /// Wraps a label's `attributedText` value in a bindable property. public var rex_attributedText: MutableProperty<NSAttributedString?> { return associatedProperty(self, key: &attributedTextKey, initial: { $0.attributedText }, setter: { $0.attributedText = $1 }) } /// Wraps a label's `textColor` value in a bindable property. public var rex_textColor: MutableProperty<UIColor> { return associatedProperty(self, key: &textColorKey, initial: { $0.textColor }, setter: { $0.textColor = $1 }) } } private var textKey: UInt8 = 0 private var attributedTextKey: UInt8 = 0 private var textColorKey: UInt8 = 0
mit
4e91cf4905962523f94148466a484c97
33.096774
132
0.678335
3.843636
false
false
false
false
elkanaoptimove/OptimoveSDK
OptimoveSDK/Optimove Components/OptiPush/Registrar/Builder/MbaasRequestBody.swift
1
3551
// // UserPushToken.swift // OptimoveSDK // // Created by Elkana Orbach on 25/04/2018. // Copyright © 2018 Optimove. All rights reserved. // import Foundation struct MbaasRequestBody:Codable,CustomStringConvertible { let tenantId: Int let deviceId:String let appNs:String let osVersion:String var visitorId : String? var publicCustomerId: String? var optIn:Bool? var token: String? let operation:MbaasOperations var isConversion: Bool? var description: String { return "tenantId=\(tenantId)&deviceId=\(deviceId)&appNs=\(appNs)&osVersion=\(osVersion)&visitorId=\(visitorId ?? "" )&publicCustomerId=\(publicCustomerId ?? "")&optIn=\(optIn?.description ?? "")&token=\(token ?? "")&operation=\(operation)&isConversion=\(isConversion?.description ?? "")" } init(operation: MbaasOperations) { self.operation = operation tenantId = TenantID ?? -1 deviceId = DeviceID appNs = Bundle.main.bundleIdentifier?.replacingOccurrences(of: ".", with: "_") ?? "" osVersion = OSVersion } func toMbaasJsonBody() ->Data? { var requestJsonData = [String: Any]() switch operation { case .optIn: fallthrough case .optOut: fallthrough case .unregistration: let iOSToken = [Keys.Registration.bundleID.rawValue : appNs, Keys.Registration.deviceID.rawValue : DeviceID ] requestJsonData[Keys.Registration.iOSToken.rawValue] = iOSToken requestJsonData[Keys.Registration.tenantID.rawValue] = TenantID if let customerId = UserInSession.shared.customerID { requestJsonData[Keys.Registration.customerID.rawValue] = customerId } else { requestJsonData[Keys.Registration.visitorID.rawValue] = VisitorID } case .registration: var bundle = [String:Any]() bundle[Keys.Registration.optIn.rawValue] = UserInSession.shared.isMbaasOptIn bundle[Keys.Registration.token.rawValue] = UserInSession.shared.fcmToken let app = [appNs: bundle] var device: [String: Any] = [Keys.Registration.apps.rawValue: app] device[Keys.Registration.osVersion.rawValue] = OSVersion let ios = [deviceId: device] requestJsonData[Keys.Registration.iOSToken.rawValue] = ios requestJsonData[Keys.Registration.tenantID.rawValue] = UserInSession.shared.siteID if let customerId = UserInSession.shared.customerID { requestJsonData[Keys.Registration.origVisitorID.rawValue] = UserInSession.shared.visitorID if UserInSession.shared.isFirstConversion == nil { UserInSession.shared.isFirstConversion = true } else { UserInSession.shared.isFirstConversion = false } requestJsonData[Keys.Registration.isConversion.rawValue] = UserInSession.shared.isFirstConversion requestJsonData[Keys.Registration.customerID.rawValue] = customerId } else { requestJsonData[Keys.Registration.visitorID.rawValue] = UserInSession.shared.visitorID } } let dictionary = [operation.rawValue : requestJsonData] return try! JSONSerialization.data(withJSONObject: dictionary, options: []) } }
mit
335d4b059c21cdcba535436e242ccfb2
40.27907
295
0.621972
4.695767
false
false
false
false
Laptopmini/SwiftyArtik
Source/MessagesAPI.swift
1
21222
// // MessagesAPI.swift // SwiftyArtik // // Created by Paul-Valentin Mini on 6/12/17. // Copyright © 2017 Paul-Valentin Mini. All rights reserved. // import Foundation import PromiseKit import Alamofire open class MessagesAPI { public enum MessageType: String { case message = "message" case action = "action" } public enum MessageStatisticsInterval: String { case minute = "minute" case hour = "hour" case day = "day" case month = "month" case year = "year" } // MARK: - Messages /// Send a Message to ARTIK Cloud. /// /// - Parameters: /// - data: The message payload. /// - did: The Device's id, used as the sender. /// - timestamp: (Optional) Message timestamp. Must be a valid time: past time, present or future up to the current server timestamp grace period. Current time if omitted. /// - Returns: A `Promise<String>`, returning the resulting message's id. open class func sendMessage(data: [String:Any], fromDid did: String, timestamp: Int64? = nil) -> Promise<String> { let parameters: [String:Any] = [ "data": data, "type": MessageType.message.rawValue, "sdid": did ] return postMessage(baseParameters: parameters, timestamp: timestamp) } /// Get the messages sent by a Device using pagination. /// /// - Parameters: /// - did: The Device's id. /// - startDate: Time of the earliest possible item, in milliseconds since epoch. /// - endDate: Time of the latest possible item, in milliseconds since epoch. /// - count: The count of results, max `100` (default). /// - offset: (Optional) The offset cursor for pagination. /// - order: (Optional) The order of the results, `.ascending` if ommited. /// - fieldPresence: (Optional) Return only messages which contain the provided field names /// - Returns: A `Promise<MessagePage>` open class func getMessages(did: String, startDate: ArtikTimestamp, endDate: ArtikTimestamp, count: Int = 100, offset: String? = nil, order: PaginationOrder? = nil, fieldPresence: [String]? = nil) -> Promise<MessagePage> { let promise = Promise<MessagePage>.pending() let path = SwiftyArtikSettings.basePath + "/messages" var presenceValue: String? if let fieldPresence = fieldPresence { presenceValue = "(" + fieldPresence.map { return "+_exists_:\($0)" }.joined(separator: " ") + ")" } let parameters = APIHelpers.removeNilParameters([ "sdid": did, "startDate": startDate, "endDate": endDate, "count": count, "offset": offset, "order": order?.rawValue, "filter": presenceValue ]) APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let page = MessagePage(JSON: response) { page.count = count page.fieldPresence = fieldPresence promise.fulfill(page) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get a specific Message /// /// - Parameters: /// - mid: The Message's id. /// - uid: (Optional) The owner's user ID, required when using an `ApplicationToken`. /// - Returns: A `Promise<Message>` open class func getMessage(mid: String, uid: String? = nil) -> Promise<Message> { let promise = Promise<Message>.pending() let path = SwiftyArtikSettings.basePath + "/messages" var parameters = [ "mid": mid ] if let uid = uid { parameters["uid"] = uid } APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let data = (response["data"] as? [[String:Any]])?.first, let message = Message(JSON: data) { promise.fulfill(message) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get the presence of Messages for a given time period. /// /// - Parameters: /// - sdid: The source Device's id. /// - fieldPresence: (Optional) Return only messages which contain the provided field name /// - startDate: Time of the earliest possible item, in milliseconds since epoch. /// - endDate: Time of the latest possible item, in milliseconds since epoch. /// - interval: The grouping interval /// - Returns: A `Promise<MessagesPresence>` open class func getPresence(sdid: String?, fieldPresence: String? = nil, startDate: ArtikTimestamp, endDate: ArtikTimestamp, interval: MessageStatisticsInterval) -> Promise<MessagesPresence> { let promise = Promise<MessagesPresence>.pending() let path = SwiftyArtikSettings.basePath + "/messages/presence" let parameters = APIHelpers.removeNilParameters([ "sdid": sdid, "fieldPresence": fieldPresence, "interval": interval.rawValue, "startDate": startDate, "endDate": endDate ]) APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let presence = MessagesPresence(JSON: response) { promise.fulfill(presence) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get the latest messages sent by a Device. /// /// - Parameters: /// - did: The Device's id /// - count: The count of results, max 100 /// - fieldPresence: (Optional) Return only messages which contain the provided field names /// - Returns: A `Promise<MessagePage>` open class func getLastMessages(did: String, count: Int = 100, fieldPresence: [String]? = nil) -> Promise<MessagePage> { let promise = Promise<MessagePage>.pending() getMessages(did: did, startDate: 1, endDate: currentArtikEpochtime(), count: count, order: .descending, fieldPresence: fieldPresence).then { page -> Void in promise.fulfill(page) }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get the lastest message sent by a Device. /// /// - Parameter did: The Device's id. /// - Returns: A `Promise<Message>` open class func getLastMessage(did: String) -> Promise<Message?> { let promise = Promise<Message?>.pending() getLastMessages(did: did, count: 1).then { page -> Void in if let message = page.data.first { promise.fulfill(message) } else { promise.fulfill(nil) } }.catch { error -> Void in promise.reject(error) } return promise.promise } // MARK: - Actions /// Send an Action to a Device through ARTIK Cloud. /// /// - Parameters: /// - named: The name of the action /// - parameters: (Optional) The parameters of the action. /// - target: The Device's id receiving the action. /// - sender: (Optional) The id of the Device sending the action. /// - timestamp: (Optional) Action timestamp, a past/present/future time up to the current server timestamp grace period. Current time if omitted. /// - Returns: A `Promise<String>` returning the resulting action's id. open class func sendAction(named: String, parameters: [String:Any]? = nil, toDid target: String, fromDid sender: String? = nil, timestamp: Int64? = nil) -> Promise<String> { var parameters: [String:Any] = [ "ddid": target, "type": MessageType.action.rawValue, "data": [ "actions": [ [ "name": named, "parameters": parameters ?? [:] ] ] ] ] if let sender = sender { parameters["sdid"] = sender } return postMessage(baseParameters: parameters, timestamp: timestamp) } /// Send multiple Actions to a Device through ARTIK Cloud. /// /// - Parameters: /// - actions: A dict where the `key` is the name of the action and the `value` is its parameters. /// - target: The Device's id receiving the action. /// - sender: (Optional) The id of the Device sending the action. /// - timestamp: (Optional) Action timestamp, a past/present/future time up to the current server timestamp grace period. Current time if omitted. /// - Returns: A `Promise<String>` returning the resulting action's id. open class func sendActions(_ actions: [String:[String:Any]?], toDid target: String, fromDid sender: String? = nil, timestamp: Int64? = nil) -> Promise<String> { var data = [[String:Any]]() for (name, parameters) in actions { data.append([ "name": name, "parameters": parameters ?? [:] ]) } var parameters: [String:Any] = [ "ddid": target, "type": MessageType.action.rawValue, "data": [ "actions": data ] ] if let sender = sender { parameters["sdid"] = sender } return postMessage(baseParameters: parameters, timestamp: timestamp) } /// Get the actions sent to a Device. /// /// - Parameters: /// - did: The Device's id /// - startDate: Time of the earliest possible item, in milliseconds since epoch. /// - endDate: Time of the latest possible item, in milliseconds since epoch. /// - count: The count of results, max `100` (default). /// - offset: (Optional) The offset cursor for pagination. /// - order: (Optional) The order of the results, `.ascending` if ommited. /// - name: (Optional) Return only actions with the provided name. /// - Returns: A `Promise<MessagePage>` open class func getActions(did: String, startDate: ArtikTimestamp, endDate: ArtikTimestamp, count: Int = 100, offset: String? = nil, order: PaginationOrder? = nil, name: String? = nil) -> Promise<MessagePage> { let promise = Promise<MessagePage>.pending() let path = SwiftyArtikSettings.basePath + "/actions" let parameters = APIHelpers.removeNilParameters([ "sdid": did, "startDate": startDate, "endDate": endDate, "count": count, "offset": offset, "order": order?.rawValue, "name": name ]) APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let page = MessagePage(JSON: response) { page.count = count page.name = name promise.fulfill(page) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get a particular action sent to a Device. /// /// - Parameters: /// - mid: The Action's (message) id. /// - uid: (Optional) The owner's user ID, required when using an `ApplicationToken`. /// - Returns: A `Promise<Message>` open class func getAction(mid: String, uid: String? = nil) -> Promise<Message> { let promise = Promise<Message>.pending() let path = SwiftyArtikSettings.basePath + "/actions" var parameters = [ "mid": mid ] if let uid = uid { parameters["uid"] = uid } APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let data = (response["data"] as? [[String:Any]])?.first, let message = Message(JSON: data) { promise.fulfill(message) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get the latest actions sent to a Device. /// /// - Parameters: /// - did: The Device's id. /// - count: The count of results, max 100. /// - name: (Optional) Return only actions with the provided name. /// - Returns: A `Promise<MessagePage>` open class func getLastActions(did: String, count: Int = 100, name: String? = nil) -> Promise<MessagePage> { let promise = Promise<MessagePage>.pending() getActions(did: did, startDate: 1, endDate: currentArtikEpochtime(), count: count, order: .descending, name: name).then { page -> Void in promise.fulfill(page) }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get the latest action sent to a Device /// /// - Parameter did: The Device's id. /// - Returns: A `Promise<Message?>` open class func getLastAction(did: String) -> Promise<Message?> { let promise = Promise<Message?>.pending() getLastActions(did: did, count: 1).then { page -> Void in if let message = page.data.first { promise.fulfill(message) } else { promise.fulfill(nil) } }.catch { error -> Void in promise.reject(error) } return promise.promise } // MARK: - Analytics /// Get the sum, minimum, maximum, mean and count of message fields that are numerical. Values for `startDate` and `endDate` are rounded to start of minute, and the date range between `startDate` and `endDate` is restricted to 31 days max. /// /// - Parameters: /// - sdid: The source Device's id. /// - startDate: Time of the earliest possible item, in milliseconds since epoch. /// - endDate: Time of the latest possible item, in milliseconds since epoch. /// - field: Message field being queried for analytics. /// - Returns: A `Promise<MessageAggregates>` open class func getAggregates(sdid: String, startDate: ArtikTimestamp, endDate: ArtikTimestamp, field: String) -> Promise<MessageAggregates> { let promise = Promise<MessageAggregates>.pending() let path = SwiftyArtikSettings.basePath + "/messages/analytics/aggregates" let parameters: [String:Any] = [ "sdid": sdid, "startDate": startDate, "endDate": endDate, "field": field ] APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let aggregate = MessageAggregates(JSON: response) { promise.fulfill(aggregate) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Returns message aggregates over equal intervals, which can be used to draw a histogram. /// /// - Parameters: /// - sdid: The source Device's id. /// - startDate: Time of the earliest possible item, in milliseconds since epoch. /// - endDate: Time of the latest possible item, in milliseconds since epoch. /// - interval: Interval on histogram X-axis. /// - field: Message field being queried for histogram aggregation (histogram Y-axis). /// - Returns: A `Promise<MessageHistogram>` open class func getHistogram(sdid: String, startDate: ArtikTimestamp, endDate: ArtikTimestamp, interval: MessageStatisticsInterval, field: String) -> Promise<MessageHistogram> { let promise = Promise<MessageHistogram>.pending() let path = SwiftyArtikSettings.basePath + "/messages/analytics/histogram" let parameters: [String:Any] = [ "sdid": sdid, "startDate": startDate, "endDate": endDate, "interval": interval.rawValue, "field": field ] APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let histogram = MessageHistogram(JSON: response) { promise.fulfill(histogram) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } // MARK: - Snapshots /// Get the last received value for all Manifest fields (aka device "state") of devices. /// /// - Parameters: /// - dids: An array containing the Devices' ids. /// - includeTimestamp: (Optional) Include the timestamp of the last modification for each field. /// - Returns: A `Promise<[String:[String:Any]]>` where the `key` is the Device id and the `value` is its snapshot. open class func getSnapshots(dids: [String], includeTimestamp: Bool? = nil) -> Promise<[String:[String:Any]]> { let promise = Promise<[String:[String:Any]]>.pending() let path = SwiftyArtikSettings.basePath + "/messages/snapshots" if dids.count > 0 { var didsString = "" for did in dids { didsString += "\(did)," } APIHelpers.makeRequest(url: path, method: .get, parameters: ["sdids": didsString], encoding: URLEncoding.queryString).then { response -> Void in if let data = response["data"] as? [[String:Any]] { var result = [String:[String:Any]]() for item in data { if let sdid = item["sdid"] as? String, let data = item["data"] as? [String:Any] { result[sdid] = data } else { promise.reject(ArtikError.json(reason: .invalidItem)) return } } promise.fulfill(result) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } } else { promise.fulfill([:]) } return promise.promise } /// Get the last received value for all Manifest fields (aka device "state") of a device. /// /// - Parameters: /// - did: The Device's id. /// - includeTimestamp: (Optional) Include the timestamp of the last modification for each field. /// - Returns: A `Promise<[String:Any]>` returning the snapshot open class func getSnapshot(did: String, includeTimestamp: Bool? = nil) -> Promise<[String:Any]> { let promise = Promise<[String:Any]>.pending() getSnapshots(dids: [did], includeTimestamp: includeTimestamp).then { result -> Void in if let snapshot = result[did] { promise.fulfill(snapshot) } else { promise.fulfill([:]) } }.catch { error -> Void in promise.reject(error) } return promise.promise } // MARK: - Private Methods fileprivate class func currentArtikEpochtime() -> Int64 { return Int64(Date().timeIntervalSince1970 * 1000.0) } fileprivate class func postMessage(baseParameters: [String:Any], timestamp: Int64?) -> Promise<String> { let promise = Promise<String>.pending() let path = SwiftyArtikSettings.basePath + "/messages" var parameters = baseParameters if let timestamp = timestamp { parameters["ts"] = timestamp } APIHelpers.makeRequest(url: path, method: .post, parameters: parameters, encoding: JSONEncoding.default).then { response -> Void in if let mid = (response["data"] as? [String:Any])?["mid"] as? String { promise.fulfill(mid) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } }
mit
bcdfc854e45d88d0f796cd8ac61ae163
41.442
243
0.578154
4.524733
false
false
false
false
nastia05/TTU-iOS-Developing-Course
Lecture 3/RawRepresentable.playground/Contents.swift
1
2394
struct Location { let langitude: Double let longitude: Double } struct University: CustomStringConvertible { let name: String let acronim: String let location: Location var description: String { return acronim + " - " + name } } extension University { static var ttu: University { let ttuLocation = Location(langitude: 59.394860, longitude: 24.661367) return University(name: "Tallinn Technological University", acronim: "TTU", location: ttuLocation) } static var mipt: University { let location = Location(langitude: 55.930053, longitude: 37.518253) return University(name: "Moscow Institute of Physics and Technology", acronim: "MIPT", location: location) } } // Xcode uses CustomStringConvertible to show information on the right side let ttu = University.ttu print(ttu) // In order to compare University instances, we must support Equatable protocol func ==(lhs: University, rhs: University) -> Bool { return lhs.name == rhs.name && lhs.acronim == rhs.acronim && lhs.location.langitude == rhs.location.langitude && lhs.location.longitude == rhs.location.longitude } extension University: Equatable { } University.ttu == University.ttu University.mipt == University.ttu // we should know about Array, Dictionary, Set here // In order to use in a set extension University: Hashable { var hashValue: Int { return name.hashValue ^ acronim.hashValue ^ location.langitude.hashValue ^ location.longitude.hashValue } } let universities = Set(arrayLiteral: University.mipt, .ttu) universities.contains(.mipt) // In order to decode and encode University into some entity(of Any type), we must support RawRepresentable protocol extension University: RawRepresentable { // Idealy we should encode and decode to Dictionary type([AnyHashable : Any]) in order to grab any unknown university init?(rawValue: String) { switch rawValue { case "MIPT": self = .mipt case "TTU": self = .ttu default: return nil } } var rawValue: String { return acronim } } // Little test that encoding and deconding will return the same entity let originalCopy = University(rawValue: University.mipt.rawValue) originalCopy == University.mipt
mit
d0de8d7a7f58b37791dbf4f6a2af8260
24.741935
121
0.678363
4.120482
false
false
false
false
xnitech/nopeekgifts
NoPeekGifts/GiftsViewController.swift
1
2230
// // FirstViewController.swift // NoPeekGifts // // Created by Mark Gruetzner on 10/31/15. // Copyright © 2015 XNI Technologies, LLC. All rights reserved. // import UIKit class GiftsViewController: UITableViewController { 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. } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return giftMgr.gifts.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("GiftCell", forIndexPath: indexPath) let gift = giftMgr.gifts[indexPath.row] as Gift cell.textLabel?.text = gift.name cell.detailTextLabel?.text = gift.desc return cell } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { giftMgr.gifts.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } @IBAction func cancelToGiftsViewController(segue:UIStoryboardSegue) { } @IBAction func saveGiftDetail(segue:UIStoryboardSegue) { if let giftDetailsViewController = segue.sourceViewController as? GiftDetailsViewController { if let gift = giftDetailsViewController.giftDetails { // Add gift giftMgr.addGift(gift) // Update the tableView let indexPath = NSIndexPath(forRow: giftMgr.gifts.count-1, inSection: 0) tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } } }
mit
319eaa037f34ed2ee84517f9b1bc83c1
31.304348
154
0.69179
5.410194
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Layers/RGB renderer/RGBRendererViewController.swift
1
2909
// // Copyright 2016 Esri. // // 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 UIKit import ArcGIS class RGBRendererViewController: UIViewController, RGBRendererSettingsViewControllerDelegate { @IBOutlet var mapView: AGSMapView! private var rasterLayer: AGSRasterLayer? override func viewDidLoad() { super.viewDidLoad() // add the source code button item to the right of navigation bar (navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["RGBRendererViewController", "RGBRendererSettingsViewController", "OptionsTableViewController"] // create raster let raster = AGSRaster(name: "Shasta", extension: "tif") // create raster layer using the raster let rasterLayer = AGSRasterLayer(raster: raster) self.rasterLayer = rasterLayer // initialize a map with raster layer as the basemap let map = AGSMap(basemap: AGSBasemap(baseLayer: rasterLayer)) // assign map to the map view mapView.map = map } // MARK: - RGBRendererSettingsViewControllerDelegate func rgbRendererSettingsViewController(_ rgbRendererSettingsViewController: RGBRendererSettingsViewController, didSelectStretchParameters parameters: AGSStretchParameters) { let renderer = AGSRGBRenderer(stretchParameters: parameters, bandIndexes: [], gammas: [], estimateStatistics: true) rasterLayer?.renderer = renderer } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let navController = segue.destination as? UINavigationController, let controller = navController.viewControllers.first as? RGBRendererSettingsViewController { controller.preferredContentSize = CGSize(width: 375, height: 135) controller.delegate = self if let parameters = (rasterLayer?.renderer as? AGSRGBRenderer)?.stretchParameters { controller.setupForParameters(parameters) } navController.presentationController?.delegate = self } } } extension RGBRendererViewController: UIAdaptivePresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } }
apache-2.0
7a2cee454c7713b983fc42aaa3d8d278
41.15942
180
0.715022
5.357274
false
false
false
false
PigDogBay/swift-utils
SwiftUtils/MockIAP.swift
1
2137
// // MockIAP.swift // SwiftUtils // // Created by Mark Bailey on 06/07/2016. // Copyright © 2016 MPD Bailey Technology. All rights reserved. // import Foundation open class MockIAP : IAPInterface { open var observable: IAPObservable open var serverProducts : [IAPProduct] = [] open var retrievedProducts : [IAPProduct] = [] open var canMakePaymentsFlag = true open var failPurchaseFlag = false open var delay : Int64 = 1 public init(){ observable = IAPObservable() } open func canMakePayments() -> Bool { return canMakePaymentsFlag } open func requestPurchase(_ productID: String) { let time = DispatchTime.now() + Double(delay * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC) DispatchQueue.global(qos: .default).asyncAfter(deadline: time) { if self.failPurchaseFlag { self.observable.onPurchaseRequestFailed(productID) } else { self.observable.onPurchaseRequestCompleted(productID) } } } open func restorePurchases() { let time = DispatchTime.now() + Double(delay * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC) DispatchQueue.global(qos: .default).asyncAfter(deadline: time) { for p in self.serverProducts { self.observable.onRestorePurchaseCompleted(p.id) } } } open func requestProducts() { print("request Products") let time = DispatchTime.now() + Double(delay * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC) DispatchQueue.global(qos: .default).asyncAfter(deadline: time) { print("request Products - Dispatched") self.retrievedProducts = self.serverProducts self.observable.onProductsRequestCompleted() } } open func getProduct(_ productID : String) -> IAPProduct? { for p in retrievedProducts { if p.id == productID { return p } } return nil } }
apache-2.0
968229ff43ddcd4726b4d82f5563a8c2
27.864865
98
0.581929
4.506329
false
false
false
false
acsalu/Keymochi
Keymochi/DataChunk.swift
2
6836
// // DataChunk.swift // Keymochi // // Created by Huai-Che Lu on 3/17/16. // Copyright © 2016 Cornell Tech. All rights reserved. // import Foundation import RealmSwift import PAM class DataChunk: Object { fileprivate dynamic var emotionDescription: String? dynamic var symbolKeyEventSequence: SymbolKeyEventSequence? dynamic var backspaceKeyEventSequence: BackspaceKeyEventSequence? dynamic var accelerationDataSequence: MotionDataSequence? dynamic var gyroDataSequence: MotionDataSequence? dynamic var realmId: String = UUID().uuidString dynamic var createdAt: Date = Date() dynamic var parseId: String? dynamic var firebaseKey: String? dynamic var appVersion: String? = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String dynamic var emotionPosition: Int = 0 dynamic var sentiment: Float = 0.0 var emotion: Emotion { return Emotion(position: Position(emotionPosition))! } override class func primaryKey() -> String? { return "realmId" } override var description: String { let symbolKeyEventCount = (symbolKeyEventSequence != nil) ? symbolKeyEventSequence!.keyEvents.count : -1 let accelerationDataPointCount = (accelerationDataSequence != nil) ? accelerationDataSequence!.motionDataPoints.count : -1 let gyroDataPointCount = (gyroDataSequence != nil) ? gyroDataSequence!.motionDataPoints.count : -1 return String(format: "[DataChunk] %d symbols, %d acceleration dps, %d gyro dps", symbolKeyEventCount, accelerationDataPointCount, gyroDataPointCount) } var startTime: Double? { return keyEvents?.first?.downTime } var endTime: Double? { return keyEvents?.last?.upTime } var keyEvents: [KeyEvent]? { guard symbolKeyEventSequence != nil && backspaceKeyEventSequence != nil else { return nil } let symbolKeyEvents: [SymbolKeyEvent] = (symbolKeyEventSequence != nil) ? Array(symbolKeyEventSequence!.keyEvents) : [] let backspaceKeyEvents: [BackspaceKeyEvent] = (backspaceKeyEventSequence != nil) ? Array(backspaceKeyEventSequence!.keyEvents) : [] let keyEvents = ((symbolKeyEvents as [KeyEvent]) + (backspaceKeyEvents as [KeyEvent])).sorted { $0.downTime < $1.downTime } return keyEvents } var accelerationDataPoints: [MotionDataPoint]? { return accelerationDataSequence?.motionDataPoints.map { $0 } } var gyroDataPoints: [MotionDataPoint]? { return gyroDataSequence?.motionDataPoints.map { $0 } } convenience init(emotion: Emotion) { // convenience init(emotion: Emotion, sentiment: Float) { self.init() self.emotionPosition = Int(emotion.position) } // convenience init(emotion: Emotion, sentiment: Sentiment) { // self.init() // self.emotionPosition = Int(emotion.position) // } } extension Array { var pair: [(Element, Element)]? { guard count > 1 else { return nil } return Array<(Element, Element)>(zip(self[0..<count-1], self[1..<count])) } } // MARK: - Stats extension DataChunk { var symbolCounts: [String: Int]? { guard let symbols = symbolKeyEventSequence?.keyEvents.map({ $0.key }) else { return nil } var symbolCounts = [String: Int]() for symbol in symbols { if let symbol = symbol { if symbolCounts[symbol] == nil { symbolCounts[symbol] = 1 } else { symbolCounts[symbol]! += 1 } } } return symbolCounts } var totalNumberOfDeletions: Int? { return backspaceKeyEventSequence?.keyEvents .map { $0.numberOfDeletions } .reduce(0, +) } var interTapDistances: [Double]? { guard let keyEvents = keyEvents else { return nil } return keyEvents.pair? .map { return $0.1.downTime - $0.0.upTime } } var tapDurations: [Double]? { return keyEvents?.map { $0.duration } } var accelerationMagnitudes: [Double]? { return accelerationDataPoints?.map { $0.magnitude } } var gyroMagnitudes: [Double]? { return gyroDataPoints?.map { $0.magnitude } } var dictionaryForm: [String: Any]? { guard let totalNumberOfDeletions = totalNumberOfDeletions, let interTapDistances = interTapDistances, let tapDurations = tapDurations, let accelerationMagnitudes = accelerationMagnitudes, let gyroMagnitudes = gyroMagnitudes, let appVersion = appVersion, let symbolCounts = symbolCounts else { return nil } var dictionary = [String: Any]() dictionary["emotion"] = emotion.tag dictionary["totalNumDel"] = NSNumber(value: totalNumberOfDeletions) dictionary["interTapDist"] = NSArray(array: interTapDistances.map { NSNumber(value: $0) }) dictionary["tapDur"] = NSArray(array: tapDurations.map { NSNumber(value: $0) }) dictionary["accelMag"] = NSArray(array: accelerationMagnitudes.map { NSNumber(value: $0) }) dictionary["gyroMag"] = NSArray(array: gyroMagnitudes.map { NSNumber(value: $0) }) dictionary["appVer"] = NSString(string: appVersion) dictionary["createdAtSince1970"] = createdAt.timeIntervalSince1970 dictionary["sentiment"] = sentiment var puncuationCount = 0 for (symbol, count) in symbolCounts { for scalar in symbol.unicodeScalars { let value = scalar.value if (value >= 65 && value <= 90) || (value >= 97 && value <= 122) || (value >= 48 && value <= 57) { dictionary["symbol_\(symbol)"] = NSNumber(value: count) } else { puncuationCount += count var key: String! switch symbol { case " ": key = "symbol_space" case "!": key = "symbol_exclamation_mark" case ".": key = "symbol_period" case "?": key = "symbol_question_mark" default: continue } dictionary[key] = NSNumber(value: count) } } dictionary["symbol_punctuation"] = NSNumber(value: puncuationCount) } return dictionary } }
bsd-3-clause
c8a9260352de132d0d372f0d97bb2806
34.231959
131
0.583175
4.668716
false
false
false
false
121372288/Refresh
Refresh/Base/RefreshHeader.swift
1
6146
// // RefreshHeaderView.swift // RefreshDemo // // Created by 马磊 on 2016/10/18. // Copyright © 2016年 MLCode.com. All rights reserved. // import UIKit import AudioToolbox open class RefreshHeader: RefreshComponent { public required init(_ refreshingCallback: (()->())?) { super.init() refreshingBlock = refreshingCallback } public required init(_ target: Any?, action: Selector) { super.init() addRefreshingTarget(target, action: action) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** 这个key用来存储上一次下拉刷新成功的时间 */ var lastUpdatedTimeKey: String = RefreshHeaderTimeKey /** 上一次下拉刷新成功的时间 */ open var lastUpdatedTime: Date? { return UserDefaults.standard.object(forKey: lastUpdatedTimeKey) as? Date } var insetTDelta: CGFloat = 0 /** 忽略多少scrollView的contentInset的top */ open var ignoredScrollViewContentInsetTop: CGFloat = 0 open override func prepare() { super.prepare() frame.size.height = RefreshHeaderHeight } open override func placeSubViews() { super.placeSubViews() // 设置y值(当自己的高度发生改变了,肯定要重新调整Y值,所以放到placeSubviews方法中设置y值) self.frame.origin.y = -self.frame.size.height - self.ignoredScrollViewContentInsetTop } open override func scrollView(contentOffset changed: [NSKeyValueChangeKey : Any]?) { super.scrollView(contentOffset: changed) guard let scrollView = scrollView else { return } // 在刷新的refreshing状态 switch state { case .refreshing: if self.window == nil { return } // sectionheader停留解决 let scrollViewOriginalInset = self.scrollViewOriginalInset ?? .zero var insetT = max(-scrollView.contentOffset.y, scrollViewOriginalInset.top) insetT = min(insetT, frame.size.height + scrollViewOriginalInset.top) scrollView.mlInset.top = insetT insetTDelta = scrollViewOriginalInset.top - insetT default: // 跳转到下一个控制器时,contentInset可能会变 scrollViewOriginalInset = scrollView.mlInset // 当前的contentOffset let offsetY = scrollView.contentOffset.y // 头部控件刚好出现的offsetY let happenOffsetY = -(scrollViewOriginalInset?.top ?? 0) // 如果是向上滚动到看不见头部控件,直接返回 // >= -> > if offsetY > happenOffsetY { return } // 普通 和 即将刷新 的临界点 let normal2pullingOffsetY = happenOffsetY - self.frame.size.height let pullingPercent = (happenOffsetY - offsetY) / self.frame.size.height if scrollView.isDragging { // 如果正在拖拽 self.pullingPercent = pullingPercent if state == .idle || state == .willRefresh, offsetY < normal2pullingOffsetY { // 转为即将刷新状态 state = .pulling } else if state == .pulling, offsetY >= normal2pullingOffsetY { // 转为普通状态 state = .idle } } else if state == .pulling {// 即将刷新 && 手松开 // 开始刷新 beginRefreshing() } else if pullingPercent < 1 { self.pullingPercent = pullingPercent } } } public override var state: RefreshState { didSet { if oldValue == state { return } if state == .pulling { //建立的SystemSoundID对象 if #available(iOS 10.0, *) { let impactLight = UIImpactFeedbackGenerator(style: .light) impactLight.impactOccurred() } else { AudioServicesPlaySystemSound(1519) } } switch state { case .idle: if oldValue != .refreshing { return } // 保存刷新时间 UserDefaults.standard.set(Date(), forKey: lastUpdatedTimeKey) UserDefaults.standard.synchronize() // 恢复inset和offset UIView.animate(withDuration: RefreshSlowAnimationDuration, animations: { self.scrollView?.mlInset.top += self.insetTDelta // 自动调整透明度 if self.isAutomaticallyChangeAlpha == true { self.alpha = 0.0 } }) { (isFinished) in self.pullingPercent = 0.0 self.endRefreshingCompletionBlock?() } case .refreshing: DispatchQueue.main.async { UIView.animate(withDuration: RefreshFastAnimationDuration, animations: { if self.scrollView?.panGestureRecognizer.state != .cancelled { let top = (self.scrollViewOriginalInset?.top ?? 0) + self.frame.size.height // 增加滚动区域top self.scrollView?.mlInset.top = top // 设置滚动位置 var offset = (self.scrollView?.contentOffset) ?? .zero offset.y = -top self.scrollView?.setContentOffset(offset, animated: false) } }, completion: { (isFinished) in self.executeRefreshingCallback() }) } default: break } } } }
mit
2d028f354808d9608850005f6b41cf8e
34.621118
103
0.525196
5.310185
false
false
false
false
kousun12/RxSwift
RxExample/RxExample/Services/ReachabilityService.swift
6
1538
// // ReachabilityService.swift // RxExample // // Created by Vodovozov Gleb on 22.10.2015. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift #endif public enum ReachabilityStatus { case Reachable, Unreachable } class ReachabilityService { private let reachabilityRef = try! Reachability.reachabilityForInternetConnection() private let _reachabilityChangedSubject = PublishSubject<ReachabilityStatus>() private var reachabilityChanged: Observable<ReachabilityStatus> { get { return _reachabilityChangedSubject.asObservable() } } // singleton static let sharedReachabilityService = ReachabilityService() init(){ reachabilityRef.whenReachable = { reachability in self._reachabilityChangedSubject.on(.Next(.Reachable)) } reachabilityRef.whenUnreachable = { reachability in self._reachabilityChangedSubject.on(.Next(.Unreachable)) } try! reachabilityRef.startNotifier() } } extension ObservableConvertibleType { func retryOnBecomesReachable(valueOnFailure:E, reachabilityService: ReachabilityService) -> Observable<E> { return self.asObservable() .catchError { (e) -> Observable<E> in reachabilityService.reachabilityChanged .filter { $0 == .Reachable } .flatMap { _ in failWith(e) } .startWith(valueOnFailure) } .retry() } }
mit
c5f58f40b604b0c14f8b99e166c3cfee
26.446429
111
0.654522
5.336806
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/Sections/Home/SDWebImageManager+HiPDA.swift
1
1546
// // SDWebImageManag+HiPDA.swift // HiPDA // // Created by leizh007 on 2017/5/23. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation import SDWebImage typealias ImageDataLoadResult = HiPDA.Result<Data, NSError> typealias ImageDataLoadCompletion = (ImageDataLoadResult) -> Void extension SDWebImageManager { func loadImageData(with url: URL?, completed completedBlock: ImageDataLoadCompletion? = nil) { guard let url = url, let completedBlock = completedBlock else { return } SDWebImageManager.shared().loadImage(with: url, options: [.highPriority], progress: nil) { (image, data, error, _, _, _) in if let error = error { completedBlock(.failure(error as NSError)) } else if let data = data { completedBlock(.success(data)) } else if let image = image { DispatchQueue.global().async { if let data = UIImageJPEGRepresentation(image, 1.0) { DispatchQueue.main.async { completedBlock(.success(data)) } } else { DispatchQueue.main.async { completedBlock(.failure(NSError(domain: C.URL.HiPDA.image, code: -1, userInfo: nil))) } } } } else { completedBlock(.failure(NSError(domain: C.URL.HiPDA.image, code: -1, userInfo: nil))) } } } }
mit
1b1a241a2bd7d8d4582ec99bfde04725
37.575
131
0.552171
4.747692
false
false
false
false
jakub-tucek/fit-checker-2.0
fit-checker/networking/EduxRetrier.swift
1
2436
// // EduxRetrier.swift // fit-checker // // Created by Josef Dolezal on 20/01/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import Foundation import Alamofire /// Allows to retry failed operations. If operation failed because of /// missing cookies (uh, authorization) retrier tries to login /// user with stored credential and if it's successfull, calls original /// request again. class EduxRetrier: RequestRetrier { /// Network request manager - private weak var networkController: NetworkController? /// Thread safe token refreshning indicator private var isRefreshing = false /// Synchronizing queue private let accessQueue = DispatchQueue(label: "EduxRetrier") init(networkController: NetworkController) { self.networkController = networkController } /// Determines wheter /// /// - Parameters: /// - manager: Requests session manager /// - request: Failed request /// - error: Request error /// - completion: Retry decision public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { Logger.shared.info("Ooops, request failed") // Run validation on serial queue accessQueue.async { [weak self] in let keychain = Keechain(service: .edux) // Retry only on recognized errors guard case EduxValidators.ValidationError.badCredentials = error else { Logger.shared.info("Unrecognized error, not retrying.") completion(false, 0.0) return } guard self?.isRefreshing == false, let networkController = self?.networkController, let (username, password) = keychain.getAccount() else { return } Logger.shared.info("Retrying request") self?.isRefreshing = true let promise = networkController.authorizeUser(with: username, password: password) // Try to authorize user promise.success = { completion(true, 0.0) } promise.failure = { completion(false, 0.0) } self?.isRefreshing = false } } }
mit
cfce5cc027650866ab1d31ee7b5d8665
28.337349
81
0.589322
5.236559
false
false
false
false
chrisbudro/GrowlerHour
growlers/DisplayImageService.swift
1
888
// // DisplayImageService.swift // growlers // // Created by Chris Budro on 10/13/15. // Copyright © 2015 chrisbudro. All rights reserved. // import UIKit import AlamofireImage let kDisplayImageFadeDuration = 0.4 class DisplayImageService { class func setImageView(imageView: UIImageView?, withUrlString urlString: String?, placeholderImage: UIImage?) { if let imageView = imageView { if let urlString = urlString, url = NSURL(string: urlString) { let size = imageView.frame.size let filter = AspectScaledToFillSizeFilter(size: size) imageView.af_setImageWithURL(url, placeholderImage: nil, filter: filter, imageTransition: .CrossDissolve(kDisplayImageFadeDuration)) } else { imageView.contentMode = .ScaleAspectFit imageView.image = placeholderImage } } } }
mit
e47727ef40c05edf67b4c3281fe55a83
28.566667
144
0.671928
4.668421
false
false
false
false
XeresRazor/FFXIVServer
Sources/FFXIVServer/ZoneDatabase.swift
1
4860
// // ZoneDatabase.swift // FFXIVServer // // Created by David Green on 2/24/16. // Copyright © 2016 David Green. All rights reserved. // import Foundation import SMGOLFramework // Convenience functions func parseFloat(valueString: String) -> Float32 { guard let result = Float32(valueString) else { return 0.0 } return result } func parseVector3(vectorString: String) -> ActorVector3 { var components = vectorString.componentsSeparatedByString(", ") if components.count != 3 { return ActorVector3(0.0, 0.0, 0.0) } return (parseFloat(components[0]), parseFloat(components[1]), parseFloat(components[2])) } // MARK: Types typealias ActorVector3 = (Float32, Float32, Float32) struct ActorDefinition { var id: UInt32 = 0 var nameStringID: UInt32 = 0 var baseModelID: UInt32 = 0 var topModelID: UInt32 = 0 var pos = ActorVector3(0.0, 0.0, 0.0) } struct ZoneDefinition { typealias ActorArray = [ActorDefinition] var backgroundMusicID: UInt32 = 0 var battleMusicID: UInt32 = 0 var actors = ActorArray() } class ZoneDatabase { private let LogName = "ZoneDatabase" private let zoneLocations = [ ZoneDefLocation(zoneID: 101, name: "lanoscea"), ZoneDefLocation(zoneID: 102, name: "coerthas"), ZoneDefLocation(zoneID: 103, name: "blackshroud"), ZoneDefLocation(zoneID: 104, name: "thanalan"), ZoneDefLocation(zoneID: 105, name: "mordhona"), ZoneDefLocation(zoneID: 109, name: "rivenroad") ] private struct ZoneDefLocation { var zoneID: UInt32 var name: String } private typealias ZoneDefinitionMap = [UInt32: ZoneDefinition] private var defaultZone = ZoneDefinition() private var zones = ZoneDefinitionMap() private static var zoneLocations = [ZoneDefLocation]() init() { defaultZone.backgroundMusicID = 0x39 defaultZone.battleMusicID = 0x0D } func load() { let configPath = AppConfig.getBasePath() for zoneLocation in zoneLocations { let zoneDefFilename = "ffxivd_zone_\(zoneLocation.name).xml" let zoneDefPath = configPath + "/" + zoneDefFilename if NSFileManager.defaultManager().fileExistsAtPath(zoneDefPath) { guard let inputStream = CreateInputStandardStream(zoneDefPath) else { return } guard let zone = loadZoneDefinition(inputStream) else { return } zones[zoneLocation.zoneID] = zone } else { Log.instance().logMessage(LogName, message: "File \(zoneDefPath) doesn't exist. Not loading any data for that zone.") } } } func getZone(zoneID: UInt32) -> ZoneDefinition? { guard let zone = zones[zoneID] else { return nil } return zone } func getDefaultZone() -> ZoneDefinition? { return defaultZone } func getZoneOrDefault(zoneID: UInt32) -> ZoneDefinition? { guard let zone = getZone(zoneID) else { return getDefaultZone() } return zone } private func loadZoneDefinition(stream: Stream) -> ZoneDefinition? { var result = ZoneDefinition() guard let documentNode = ParseDocument(stream) else { print("Cannot parse zone definition file."); return result } guard let zoneNode = documentNode.select("Zone") else { print("Zone definition file doesn't contain a 'Zone' node."); return result } if let backgroundMusicID = GetAttributeIntValue(zoneNode, name: "BackgroundMusicId") { result.backgroundMusicID = UInt32(backgroundMusicID) } if let battleMusicID = GetAttributeIntValue(zoneNode, name: "BattleMusicId") { result.battleMusicID = UInt32(battleMusicID) } let actorNodes = zoneNode.selectNodes("Actors/Actor") result.actors.reserveCapacity(actorNodes.count) for actorNode in actorNodes { var actor = ActorDefinition() if let id = GetAttributeIntValue(actorNode, name: "Id") { actor.id = UInt32(id) } if let nameStringID = GetAttributeIntValue(actorNode, name: "NameString") { actor.nameStringID = UInt32(nameStringID) } if let baseModelID = GetAttributeIntValue(actorNode, name: "BaseModel") { actor.baseModelID = UInt32(baseModelID) } if let topModelID = GetAttributeIntValue(actorNode, name: "TopModel") { actor.topModelID = UInt32(topModelID) } if let position = GetAttributeStringValue(actorNode, name: "Position") { actor.pos = parseVector3(position) } result.actors.append(actor) } return result } }
mit
df2575a6abd9e91224d8bde570c29b58
33.460993
141
0.632229
4.281057
false
false
false
false
antoninbiret/DataSourceKit
DataSourceKit/Classes/Collection/CollectionDataSource+Sections.swift
1
2148
// // CollectionDataSource+Sections.swift // DataSourceKit // // Created by Antonin Biret on 26/09/2017. // import Foundation extension CollectionDataSource { // internal func index(of section: Section) -> Int? { // return self._mutatingSections.index(of: section) // } // public func add(item: Section.Item, in section: Section) { // if let index = self.index(of: section) { // self._mutatingSections[index].items.append(item) // } else { // fatalError() // } // } // // public func add(items: [Section.Item], in section: Section) { // if let index = self.index(of: section) { // self._mutatingSections[index].items.append(contentsOf: items) // } else { // fatalError() // } // } // // public func insert(item: Section.Item, in section: Section, at index: Int) { // if let index = self.index(of: section) { // self._mutatingSections[index].items.insert(item, at: index) // } else { // fatalError() // } // } // // public func insert(items: [Section.Item], in section: Section, from index: Int) { // if let index = self.index(of: section) { // self._mutatingSections[index].items.insert(contentsOf: items, at: index) // } else { // fatalError() // } // } // // // MARK: - Deletion // // public func removeItem(in section: Section, at index: Int) { // if let index = self.index(of: section) { // self._mutatingSections[index].items.remove(at: index) // } else { // fatalError() // } // } // // public func removeItems(in section: Section, in range: Range<Int>) { // if let index = self.index(of: section) { // self._mutatingSections[index].items.removeSubrange(range) // } else { // fatalError() // } // } // // // MARK: - Modification // // public func replace(item: Section.Item, in section: Section, at index: Int) { // if let index = self.index(of: section) { // self._mutatingSections[index].items[index] = item // } else { // fatalError() // } // } }
mit
d98c5c9e9aef5f891761b03d2bd419e7
27.263158
87
0.562849
3.377358
false
false
false
false
klundberg/swift-corelibs-foundation
Foundation/NSObjCRuntime.swift
1
11159
// 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 : ( sizeof(AnyObject.self), alignof(AnyObject.self) ), .Class : ( sizeof(AnyClass.self), alignof(AnyClass.self) ), .Char : ( sizeof(CChar.self), alignof(CChar.self) ), .UChar : ( sizeof(UInt8.self), alignof(UInt8.self) ), .Short : ( sizeof(Int16.self), alignof(Int16.self) ), .UShort : ( sizeof(UInt16.self), alignof(UInt16.self) ), .Int : ( sizeof(Int32.self), alignof(Int32.self) ), .UInt : ( sizeof(UInt32.self), alignof(UInt32.self) ), .Long : ( sizeof(Int32.self), alignof(Int32.self) ), .ULong : ( sizeof(UInt32.self), alignof(UInt32.self) ), .LongLong : ( sizeof(Int64.self), alignof(Int64.self) ), .ULongLong : ( sizeof(UInt64.self), alignof(UInt64.self) ), .Float : ( sizeof(Float.self), alignof(Float.self) ), .Double : ( sizeof(Double.self), alignof(Double.self) ), .Bool : ( sizeof(Bool.self), alignof(Bool.self) ), .CharPtr : ( sizeof(UnsafePointer<CChar>.self), alignof(UnsafePointer<CChar>.self)) ] 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 SortOptions: OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let concurrent = SortOptions(rawValue: UInt(1 << 0)) public static let stable = SortOptions(rawValue: UInt(1 << 4)) } public struct EnumerationOptions: OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let concurrent = EnumerationOptions(rawValue: UInt(1 << 0)) public static let reverse = EnumerationOptions(rawValue: UInt(1 << 1)) } public typealias Comparator = (AnyObject, AnyObject) -> ComparisonResult public let NSNotFound: Int = Int.max @noreturn internal func NSRequiresConcreteImplementation(_ fn: String = #function, file: StaticString = #file, line: UInt = #line) { fatalError("\(fn) must be overriden in subclass implementations", file: file, line: line) } @noreturn internal func NSUnimplemented(_ fn: String = #function, file: StaticString = #file, line: UInt = #line) { fatalError("\(fn) is not yet implemented", file: file, line: line) } @noreturn internal func NSInvalidArgument(_ message: String, method: String = #function, file: StaticString = #file, line: UInt = #line) { 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 } } internal protocol _CFBridgable { associatedtype CFType var _cfObject: CFType { get } } internal protocol _SwiftBridgable { associatedtype SwiftType var _swiftObject: SwiftType { get } } internal protocol _NSBridgable { associatedtype NSType var _nsObject: NSType { get } } #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).bridge() 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(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.bridge().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
13e09e18d3d55a906d860b1a13c3ab80
36.955782
571
0.638677
4.485129
false
false
false
false
PureSwift/Cacao
Sources/CacaoDemo/SwitchViewController.swift
1
820
// // SwitchViewController.swift // CacaoDemo // // Created by Alsey Coleman Miller on 6/15/17. // #if os(Linux) import Glibc #elseif os(macOS) import Darwin.C #endif import Foundation #if os(iOS) || os(tvOS) import UIKit import CoreGraphics #else import Cacao import Silica #endif final class SwitchViewController: UIViewController { // MARK: - Views private(set) weak var switchView: UISwitch! // MARK: - Loading override func loadView() { view = UIView() let switchView = UISwitch() self.switchView = switchView view.backgroundColor = UIColor.white view.addSubview(switchView) } override func viewWillLayoutSubviews() { switchView.center = view.center } }
mit
522032b3a829090f65085843f082a9bb
16.083333
52
0.609756
4.432432
false
false
false
false
marselan/patient-records
Patient-Records/Patient-Records/RecordViewController.swift
1
5194
// // RecordViewController.swift // patient_records // // Created by Mariano Arselan on 24/12/16. // Copyright © 2016 Mariano Arselan. All rights reserved. // import Foundation import UIKit class RecordViewController : UITableViewController { var record : Record? var patientRecord : PatientRecord init(withRecord patientRecord: PatientRecord) { self.record = nil self.patientRecord = patientRecord super.init(style: .grouped); } override func viewDidLoad() { self.tableView.frame = self.view.bounds self.title = patientRecord.timestamp loadData() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section{ case 0: return 1 case 1: return 1 default: return self.studies.count } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section{ case 0: return "Reason" case 1: return "Treatment" case 2: return "Studies" default: return nil } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell") if cell == nil { cell = UITableViewCell(style: .subtitle, reuseIdentifier: "LabelCell") cell?.detailTextLabel?.textColor = UIColor.lightGray if indexPath.section == 2 { cell?.accessoryType = UITableViewCellAccessoryType.disclosureIndicator } } switch indexPath.section { case 0: cell!.textLabel!.text = self.record.reason case 1: cell!.textLabel!.text = self.record.treatment default: let study : Study = studies[indexPath.row]; cell!.textLabel!.text = String(describing: study.label) let studyType : StudyType = self.studyTypes[study.studyTypeId]! //cell!.detailTextLabel!.text = studyType.aDescription } return cell! } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 2 { let backItem = UIBarButtonItem() backItem.title = "Back" navigationItem.backBarButtonItem = backItem let studyId = studies[indexPath.row].id let studyTypeId = studies[indexPath.row].studyTypeId switch studyTypeId { case 1: // X-ray scan let xRayScanViewController = XrayScanViewController(studyId) self.navigationController?.pushViewController(xRayScanViewController, animated: true) case 2: // CT scan let ctImageViewController = CtImageViewController(studyId) self.navigationController?.pushViewController(ctImageViewController, animated: true) case 3: // MRI scan let mriImageViewController = MriImageViewController(studyId) self.navigationController?.pushViewController(mriImageViewController, animated: true) default: return } } } func loadData() { let urlString = URL(string: Config.instance.backendUrl + "/PatientManager/PatientService/patient/\(self.patientRecord.patientId)/record/\(self.patientRecord.id)"); var request : URLRequest = URLRequest(url: urlString!) request.addValue(Config.instance.user, forHTTPHeaderField: "user") request.addValue(Config.instance.password, forHTTPHeaderField: "password") let config = URLSessionConfiguration.default let session = URLSession(configuration: config) let task = session.dataTask(with: request, completionHandler: {(data, response, error) in if let error = error { return } guard let response = response else { return } switch(response.httpStatusCode()) { case 200: do { guard let json = data else { return } self.record = try JSONDecoder().decode(Record.self, from: json) } catch let e { print(e) } case 404: return default: return } DispatchQueue.main.async(execute:self.tableView.reloadData()) }) task.resume() } }
gpl-3.0
65261ad152546466c34508686c4920c6
31.254658
147
0.560562
5.554011
false
false
false
false
suzuki-0000/SKPhotoBrowser
SKPhotoBrowser/SKZoomingScrollView.swift
1
11063
// // SKZoomingScrollView.swift // SKViewExample // // Created by suzuki_keihsi on 2015/10/01. // Copyright © 2015 suzuki_keishi. All rights reserved. // import UIKit open class SKZoomingScrollView: UIScrollView { var captionView: SKCaptionView! var photo: SKPhotoProtocol! { didSet { imageView.image = nil if photo != nil && photo.underlyingImage != nil { displayImage(complete: true) return } if photo != nil { displayImage(complete: false) } } } fileprivate weak var browser: SKPhotoBrowser? fileprivate(set) var imageView: SKDetectingImageView! fileprivate var tapView: SKDetectingView! fileprivate var indicatorView: SKIndicatorView! required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } convenience init(frame: CGRect, browser: SKPhotoBrowser) { self.init(frame: frame) self.browser = browser setup() } deinit { browser = nil } func setup() { // tap tapView = SKDetectingView(frame: bounds) tapView.delegate = self tapView.backgroundColor = .clear tapView.autoresizingMask = [.flexibleHeight, .flexibleWidth] addSubview(tapView) // image imageView = SKDetectingImageView(frame: frame) imageView.delegate = self imageView.contentMode = .bottom imageView.backgroundColor = .clear addSubview(imageView) // indicator indicatorView = SKIndicatorView(frame: frame) addSubview(indicatorView) // self backgroundColor = .clear delegate = self showsHorizontalScrollIndicator = SKPhotoBrowserOptions.displayHorizontalScrollIndicator showsVerticalScrollIndicator = SKPhotoBrowserOptions.displayVerticalScrollIndicator autoresizingMask = [.flexibleWidth, .flexibleTopMargin, .flexibleBottomMargin, .flexibleRightMargin, .flexibleLeftMargin] } // MARK: - override open override func layoutSubviews() { tapView.frame = bounds indicatorView.frame = bounds super.layoutSubviews() let boundsSize = bounds.size var frameToCenter = imageView.frame // horizon if frameToCenter.size.width < boundsSize.width { frameToCenter.origin.x = floor((boundsSize.width - frameToCenter.size.width) / 2) } else { frameToCenter.origin.x = 0 } // vertical if frameToCenter.size.height < boundsSize.height { frameToCenter.origin.y = floor((boundsSize.height - frameToCenter.size.height) / 2) } else { frameToCenter.origin.y = 0 } // Center if !imageView.frame.equalTo(frameToCenter) { imageView.frame = frameToCenter } } open func setMaxMinZoomScalesForCurrentBounds() { maximumZoomScale = 1 minimumZoomScale = 1 zoomScale = 1 guard let imageView = imageView else { return } let boundsSize = bounds.size let imageSize = imageView.frame.size let xScale = boundsSize.width / imageSize.width let yScale = boundsSize.height / imageSize.height var minScale: CGFloat = min(xScale.isNormal ? xScale : 1.0, yScale.isNormal ? yScale : 1.0) var maxScale: CGFloat = 1.0 let scale = max(SKMesurement.screenScale, 2.0) let deviceScreenWidth = SKMesurement.screenWidth * scale // width in pixels. scale needs to remove if to use the old algorithm let deviceScreenHeight = SKMesurement.screenHeight * scale // height in pixels. scale needs to remove if to use the old algorithm if SKPhotoBrowserOptions.longPhotoWidthMatchScreen && imageView.frame.height >= imageView.frame.width { minScale = 1.0 maxScale = 2.5 } else if imageView.frame.width < deviceScreenWidth { // I think that we should to get coefficient between device screen width and image width and assign it to maxScale. I made two mode that we will get the same result for different device orientations. if UIApplication.shared.statusBarOrientation.isPortrait { maxScale = deviceScreenHeight / imageView.frame.width } else { maxScale = deviceScreenWidth / imageView.frame.width } } else if imageView.frame.width > deviceScreenWidth { maxScale = 1.0 } else { // here if imageView.frame.width == deviceScreenWidth maxScale = 2.5 } maximumZoomScale = maxScale minimumZoomScale = minScale zoomScale = minScale // on high resolution screens we have double the pixel density, so we will be seeing every pixel if we limit the // maximum zoom scale to 0.5 // After changing this value, we still never use more maxScale /= scale if maxScale < minScale { maxScale = minScale * 2 } // reset position imageView.frame.origin = CGPoint.zero setNeedsLayout() } open func prepareForReuse() { photo = nil if captionView != nil { captionView.removeFromSuperview() captionView = nil } } open func displayImage(_ image: UIImage) { // image imageView.image = image imageView.contentMode = photo.contentMode var imageViewFrame: CGRect = .zero imageViewFrame.origin = .zero // long photo if SKPhotoBrowserOptions.longPhotoWidthMatchScreen && image.size.height >= image.size.width { let imageHeight = SKMesurement.screenWidth / image.size.width * image.size.height imageViewFrame.size = CGSize(width: SKMesurement.screenWidth, height: imageHeight) } else { imageViewFrame.size = image.size } imageView.frame = imageViewFrame contentSize = imageViewFrame.size setMaxMinZoomScalesForCurrentBounds() } // MARK: - image open func displayImage(complete flag: Bool) { // reset scale maximumZoomScale = 1 minimumZoomScale = 1 zoomScale = 1 if !flag { if photo.underlyingImage == nil { indicatorView.startAnimating() } photo.loadUnderlyingImageAndNotify() } else { indicatorView.stopAnimating() } if let image = photo.underlyingImage, photo != nil { displayImage(image) } else { // change contentSize will reset contentOffset, so only set the contentsize zero when the image is nil contentSize = CGSize.zero } setNeedsLayout() } open func displayImageFailure() { indicatorView.stopAnimating() } // MARK: - handle tap open func handleDoubleTap(_ touchPoint: CGPoint) { if let browser = browser { NSObject.cancelPreviousPerformRequests(withTarget: browser) } if zoomScale > minimumZoomScale { // zoom out setZoomScale(minimumZoomScale, animated: true) } else { // zoom in // I think that the result should be the same after double touch or pinch /* var newZoom: CGFloat = zoomScale * 3.13 if newZoom >= maximumZoomScale { newZoom = maximumZoomScale } */ let zoomRect = zoomRectForScrollViewWith(maximumZoomScale, touchPoint: touchPoint) zoom(to: zoomRect, animated: true) } // delay control browser?.hideControlsAfterDelay() } } // MARK: - UIScrollViewDelegate extension SKZoomingScrollView: UIScrollViewDelegate { public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } public func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { browser?.cancelControlHiding() } public func scrollViewDidZoom(_ scrollView: UIScrollView) { setNeedsLayout() layoutIfNeeded() } } // MARK: - SKDetectingImageViewDelegate extension SKZoomingScrollView: SKDetectingViewDelegate { func handleSingleTap(_ view: UIView, touch: UITouch) { guard let browser = browser else { return } guard SKPhotoBrowserOptions.enableZoomBlackArea == true else { return } if browser.areControlsHidden() == false && SKPhotoBrowserOptions.enableSingleTapDismiss == true { browser.determineAndClose() } else { browser.toggleControls() } } func handleDoubleTap(_ view: UIView, touch: UITouch) { if SKPhotoBrowserOptions.enableZoomBlackArea == true { let needPoint = getViewFramePercent(view, touch: touch) handleDoubleTap(needPoint) } } } // MARK: - SKDetectingImageViewDelegate extension SKZoomingScrollView: SKDetectingImageViewDelegate { func handleImageViewSingleTap(_ touchPoint: CGPoint) { guard let browser = browser else { return } if SKPhotoBrowserOptions.enableSingleTapDismiss { browser.determineAndClose() } else { browser.toggleControls() } } func handleImageViewDoubleTap(_ touchPoint: CGPoint) { handleDoubleTap(touchPoint) } } private extension SKZoomingScrollView { func getViewFramePercent(_ view: UIView, touch: UITouch) -> CGPoint { let oneWidthViewPercent = view.bounds.width / 100 let viewTouchPoint = touch.location(in: view) let viewWidthTouch = viewTouchPoint.x let viewPercentTouch = viewWidthTouch / oneWidthViewPercent let photoWidth = imageView.bounds.width let onePhotoPercent = photoWidth / 100 let needPoint = viewPercentTouch * onePhotoPercent var Y: CGFloat! if viewTouchPoint.y < view.bounds.height / 2 { Y = 0 } else { Y = imageView.bounds.height } let allPoint = CGPoint(x: needPoint, y: Y) return allPoint } func zoomRectForScrollViewWith(_ scale: CGFloat, touchPoint: CGPoint) -> CGRect { let w = frame.size.width / scale let h = frame.size.height / scale let x = touchPoint.x - (h / max(SKMesurement.screenScale, 2.0)) let y = touchPoint.y - (w / max(SKMesurement.screenScale, 2.0)) return CGRect(x: x, y: y, width: w, height: h) } }
mit
940cb8578ad56c4fcad2d33ba489e39c
31.727811
211
0.604863
5.419892
false
false
false
false
carlo-/ipolito
iPoliTO2/CareerViewController.swift
1
22755
// // GradesViewController.swift // iPoliTO2 // // Created by Carlo Rapisarda on 30/07/2016. // Copyright © 2016 crapisarda. All rights reserved. // import UIKit import Charts class CareerViewController: UITableViewController { var status: PTViewControllerStatus = .loggedOut { didSet { statusDidChange() } } var temporaryGrades: [PTTemporaryGrade] = [] { didSet { tableView.reloadData() } } var passedExams: [PTExam] = [] { didSet { examsDidChange() } } fileprivate var sortedExams: [PTExam] = [] fileprivate var currentSorting: PTExamSorting = PTExamSorting.defaultValue fileprivate var canShowCareerDetails: Bool { // Needs at least 1 exam return passedExams.count > 0 } fileprivate var canShowGraph: Bool { // Needs at least 1 numerical grade return passedExams.contains(where: { $0.grade != .passed }) } fileprivate var graphCell: PTGraphCell? fileprivate var detailsCell: PTCareerDetailsCell? @IBOutlet fileprivate var sortButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() if #available(iOS 11.0, *) { // Disable use of 'large title' display mode navigationItem.largeTitleDisplayMode = .never } // Removes annoying row separators after the last cell tableView.tableFooterView = UIView() setupRefreshControl() reloadSpecialCells() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { _ in self.tableView.backgroundView?.setNeedsDisplay() }, completion: nil) } func statusDidChange() { if status != .fetching && status != .logginIn { refreshControl?.endRefreshing() } let isTableEmpty = temporaryGrades.isEmpty && passedExams.isEmpty if isTableEmpty { tableView.isScrollEnabled = false navigationItem.titleView = nil let refreshButton = UIButton(type: .system) refreshButton.addTarget(self, action: #selector(refreshButtonPressed), for: .touchUpInside) switch status { case .logginIn: tableView.backgroundView = PTLoadingTableBackgroundView(frame: view.bounds, title: ~"ls.generic.status.loggingIn") case .offline: refreshButton.setTitle(~"ls.generic.alert.retry", for: .normal) tableView.backgroundView = PTSimpleTableBackgroundView(frame: view.bounds, title: ~"ls.generic.status.offline", button: refreshButton) case .error: refreshButton.setTitle(~"ls.generic.alert.retry", for: .normal) tableView.backgroundView = PTSimpleTableBackgroundView(frame: view.bounds, title: ~"ls.generic.status.couldNotRetrieve", button: refreshButton) case .ready: refreshButton.setTitle(~"ls.generic.refresh", for: .normal) tableView.backgroundView = PTSimpleTableBackgroundView(frame: view.bounds, title: ~"ls.careerVC.status.emptyCareer", button: refreshButton) navigationItem.titleView = PTSession.shared.lastUpdateTitleView(title: ~"ls.careerVC.title") default: tableView.backgroundView = nil } } else { tableView.isScrollEnabled = true tableView.backgroundView = nil switch status { case .logginIn: navigationItem.titleView = PTLoadingTitleView(withTitle: ~"ls.generic.status.loggingIn") case .fetching: navigationItem.titleView = PTLoadingTitleView(withTitle: ~"ls.careerVC.status.loading") case .offline: navigationItem.titleView = PTSession.shared.lastUpdateTitleView(title: ~"ls.generic.status.offline") default: navigationItem.titleView = PTSession.shared.lastUpdateTitleView(title: ~"ls.careerVC.title") } } } func examsDidChange() { OperationQueue().addOperation { [unowned self] _ in self.resortExams() OperationQueue.main.addOperation { self.updateSortButton() self.reloadSpecialCells() self.tableView.reloadData() } } } func setupRefreshControl() { refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(refreshControlActuated), for: .valueChanged) } @objc func refreshControlActuated() { if PTSession.shared.isBusy { refreshControl?.endRefreshing() } else { (UIApplication.shared.delegate as! AppDelegate).login() } } @objc func refreshButtonPressed() { (UIApplication.shared.delegate as! AppDelegate).login() } private func reloadSpecialCells() { if detailsCell == nil { detailsCell = tableView.dequeueReusableCell(withIdentifier: PTCareerDetailsCell.identifier) as? PTCareerDetailsCell } if graphCell == nil { graphCell = tableView.dequeueReusableCell(withIdentifier: PTGraphCell.identifier) as? PTGraphCell graphCell?.setupChart() } detailsCell?.configure(withStudentInfo: PTSession.shared.studentInfo) graphCell?.configure(withExams: passedExams) } func handleTabBarItemSelection(wasAlreadySelected: Bool) { if wasAlreadySelected { if #available(iOS 11.0, *) { tableView.setContentOffset(CGPoint(x: 0, y: -64), animated: true) } else { tableView.setContentOffset(CGPoint(x: 0, y: -tableView.contentInset.top), animated: true) } } } private func updateSortButton() { sortButton.isEnabled = (passedExams.count > 0) } @IBAction func sortPressed(_ sender: UIBarButtonItem) { let actionSheet = UIAlertController(title: ~"ls.careerVC.sorting.sortBy", message: nil, preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: ~"ls.careerVC.sorting.date", style: .default, handler: { _ in self.sortExams(.byDate) self.tableView.reloadData() })) actionSheet.addAction(UIAlertAction(title: ~"ls.careerVC.sorting.credits", style: .default, handler: { _ in self.sortExams(.byCredits) self.tableView.reloadData() })) actionSheet.addAction(UIAlertAction(title: ~"ls.careerVC.sorting.grade", style: .default, handler: { _ in self.sortExams(.byGrade) self.tableView.reloadData() })) actionSheet.addAction(UIAlertAction(title: ~"ls.careerVC.sorting.name", style: .default, handler: { _ in self.sortExams(.byName) self.tableView.reloadData() })) actionSheet.addAction(UIAlertAction(title: ~"ls.generic.alert.cancel", style: .cancel, handler: nil)) present(actionSheet, animated: true, completion: nil) } fileprivate func resortExams() { sortExams(currentSorting) } fileprivate func sortExams(_ sorting: PTExamSorting, remember: Bool = true) { switch sorting { case .byDate: sortedExams = passedExams.sorted() { $0.date > $1.date } case .byCredits: sortedExams = passedExams.sorted() { $0.credits > $1.credits } case .byGrade: sortedExams = passedExams.sorted() { $0.grade.rawValue > $1.grade.rawValue } case .byName: sortedExams = passedExams.sorted() { $0.name < $1.name } } currentSorting = sorting if remember { sorting.setAsDefault() } } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { if tableView.cellForRow(at: indexPath)?.selectionStyle == .none { return nil } else { return indexPath } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let section = indexPath.section let row = indexPath.row switch section { case 0: (cell as? PTTemporaryGradeCell)?.setTemporaryGrade(temporaryGrades[row]) case 1: (cell as? PTGradeCell)?.setExam(sortedExams[row]) default: return } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let section = indexPath.section switch section { case 0: return tableView.dequeueReusableCell(withIdentifier: PTTemporaryGradeCell.identifier, for: indexPath) case 1: return tableView.dequeueReusableCell(withIdentifier: PTGradeCell.identifier, for: indexPath) case 2: return detailsCell! default: return graphCell! } } override func numberOfSections(in tableView: UITableView) -> Int { return 4 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return temporaryGrades.count > 0 ? ~"ls.careerVC.section.tempGrades" : nil case 1: return sortedExams.count > 0 ? ~"ls.careerVC.section.grades" : nil case 2: return canShowCareerDetails ? ~"ls.careerVC.section.details" : nil case 3: return canShowGraph ? ~"ls.careerVC.section.overview" : nil default: return nil } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return temporaryGrades.count case 1: return sortedExams.count case 2: return canShowCareerDetails ? 1 : 0 case 3: return canShowGraph ? 1 : 0 default: return 0 } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let section = indexPath.section switch section { case 0: return PTTemporaryGradeCell.estimatedHeight(temporaryGrade: temporaryGrades[indexPath.row], rowWidth: tableView.frame.width) case 1: return PTGradeCell.height case 2: return PTCareerDetailsCell.height default: return PTGraphCell.height } } } private enum PTExamSorting: Int { private static let udKey = "examSorting" case byName = 0, byGrade, byCredits, byDate static var defaultValue: PTExamSorting { let rawValue = UserDefaults().integer(forKey: PTExamSorting.udKey) return PTExamSorting(rawValue: rawValue) ?? .byName } func setAsDefault() { UserDefaults().set(self.rawValue, forKey: PTExamSorting.udKey) } } class PTGradeCell: UITableViewCell { @IBOutlet var subjectLabel: UILabel! @IBOutlet var gradeLabel: UILabel! @IBOutlet var subtitleLabel: UILabel! static let identifier = "PTGradeCell_id" static let height: CGFloat = 70 func setExam(_ exam: PTExam) { subjectLabel.text = exam.name gradeLabel.text = exam.grade.shortDescription let formatter = DateFormatter() formatter.timeZone = TimeZone.Turin formatter.dateStyle = DateFormatter.Style.medium let dateStr = formatter.string(from: exam.date) subtitleLabel.text = dateStr+" - \(exam.credits) "+(~"ls.generic.credits") } override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .none } } class PTCareerDetailsCell: UITableViewCell { @IBOutlet var weightedAvgLabel: UILabel! @IBOutlet var cleanAvgLabel: UILabel! @IBOutlet var creditsLabel: UILabel! static let identifier = "PTCareerDetailsCell_id" static let height: CGFloat = 76 func configure(withStudentInfo studentInfo: PTStudentInfo?) { let formatter = NumberFormatter() formatter.allowsFloats = true formatter.maximumFractionDigits = 2 let blackAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 17.0), NSForegroundColorAttributeName: UIColor.iPoliTO.darkGray] let grayAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 12.0), NSForegroundColorAttributeName: UIColor.lightGray] var weightedAvgStr: String? = nil if let weightedAvg = studentInfo?.weightedAverage { weightedAvgStr = formatter.string(from: NSNumber(floatLiteral: weightedAvg)) } var cleanAvgStr: String? = nil if let cleanAvg = studentInfo?.cleanWeightedAverage { cleanAvgStr = formatter.string(from: NSNumber(floatLiteral: cleanAvg)) } var graduationMarkStr: String? = nil if let graduationMark = studentInfo?.graduationMark { graduationMarkStr = formatter.string(from: NSNumber(floatLiteral: graduationMark)) } var cleanGraduationMarkStr: String? = nil if let cleanGraduationMark = studentInfo?.cleanGraduationMark { cleanGraduationMarkStr = formatter.string(from: NSNumber(floatLiteral: cleanGraduationMark)) } var totalCreditsStr: String? = nil if let totalCreditsVal = studentInfo?.totalCredits { totalCreditsStr = String(totalCreditsVal) } var obtainedCreditsStr: String? = nil if let obtainedCreditsVal = studentInfo?.obtainedCredits { obtainedCreditsStr = String(obtainedCreditsVal) } let weightedAvgAttrib = NSAttributedString(string: weightedAvgStr ?? "??", attributes: blackAttributes) let cleanAvgAttrib = NSAttributedString(string: cleanAvgStr ?? "??", attributes: blackAttributes) let graduationMarkAttrib = NSAttributedString(string: graduationMarkStr ?? "??", attributes: blackAttributes) let cleanGraduationMarkAttrib = NSAttributedString(string: cleanGraduationMarkStr ?? "??", attributes: blackAttributes) let obtainedCreditsAttrib = NSAttributedString(string: obtainedCreditsStr ?? "??", attributes: blackAttributes) let maximumAverage = NSAttributedString(string: "/30", attributes: grayAttributes) let maximumGradMark = NSAttributedString(string: "/110", attributes: grayAttributes) let spacesAttrib = NSAttributedString(string: " ", attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 17.0)]) let totalCreditsAttrib = NSAttributedString(string: "/"+(totalCreditsStr ?? "??"), attributes: grayAttributes) let weightedAvgLabelText = NSMutableAttributedString() weightedAvgLabelText.append(weightedAvgAttrib) weightedAvgLabelText.append(maximumAverage) weightedAvgLabelText.append(spacesAttrib) weightedAvgLabelText.append(graduationMarkAttrib) weightedAvgLabelText.append(maximumGradMark) let cleanAvgLabelText = NSMutableAttributedString() cleanAvgLabelText.append(cleanAvgAttrib) cleanAvgLabelText.append(maximumAverage) cleanAvgLabelText.append(spacesAttrib) cleanAvgLabelText.append(cleanGraduationMarkAttrib) cleanAvgLabelText.append(maximumGradMark) let creditsLabelText = NSMutableAttributedString() creditsLabelText.append(obtainedCreditsAttrib) creditsLabelText.append(totalCreditsAttrib) weightedAvgLabel.attributedText = weightedAvgLabelText cleanAvgLabel.attributedText = cleanAvgLabelText creditsLabel.attributedText = creditsLabelText } } class PTTemporaryGradeCell: UITableViewCell { @IBOutlet var subjectLabel: UILabel! @IBOutlet var gradeLabel: UILabel! @IBOutlet var subtitleLabel: UILabel! @IBOutlet var messageTextView: UITextView! static let identifier = "PTTemporaryGradeCell_id" func setTemporaryGrade(_ tempGrade: PTTemporaryGrade) { subjectLabel.text = tempGrade.subjectName gradeLabel.text = tempGrade.grade?.shortDescription ?? "" messageTextView.text = tempGrade.message ?? "" var details: [String] = [] let formatter = DateFormatter() formatter.timeZone = TimeZone.Turin formatter.dateStyle = DateFormatter.Style.medium let dateStr = formatter.string(from: tempGrade.date) details.append(dateStr) if tempGrade.absent { details.append(~"ls.careerVC.tempGrade.absent") } if tempGrade.failed { details.append(~"ls.careerVC.tempGrade.failed") } let stateStr = ~"ls.careerVC.tempGrade.state"+": "+tempGrade.state details.append(stateStr) subtitleLabel.text = details.joined(separator: " - ") } class func estimatedHeight(temporaryGrade: PTTemporaryGrade, rowWidth: CGFloat) -> CGFloat { let minimumHeight: CGFloat = 70.0 let textViewWidth = rowWidth-22.0 guard let bodyText = temporaryGrade.message else { return minimumHeight } let textView = UITextView() textView.text = bodyText textView.font = UIFont.systemFont(ofSize: 13) let textViewSize = textView.sizeThatFits(CGSize(width: textViewWidth, height: CGFloat.greatestFiniteMagnitude)) return minimumHeight + textViewSize.height + 10.0 } override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .none } } class PTGraphCell: UITableViewCell { static let identifier = "PTGraphCell_id" static let height: CGFloat = 300 private var pieChart: PieChartView? private var pieChartData: PieChartData? override func draw(_ rect: CGRect) { pieChart?.frame = CGRect(origin: rect.origin, size: CGSize(width: rect.width, height: (rect.height - 10))) } func setupChart() { if pieChart == nil { pieChart = PieChartView() pieChart?.noDataText = ~"ls.careerVC.chart.noData" pieChart?.descriptionText = "" pieChart?.drawEntryLabelsEnabled = false pieChart?.usePercentValuesEnabled = false pieChart?.transparentCircleRadiusPercent = 0.6 pieChart?.legend.horizontalAlignment = .center pieChart?.setExtraOffsets(left: 0, top: 0, right: 0, bottom: -10) pieChart?.isUserInteractionEnabled = false addSubview(pieChart!) } if let data = pieChartData { pieChart?.data = data } } func configure(withExams exams: [PTExam]) { guard !(exams.isEmpty) else { return; } var n18_20 = 0.0 var n21_23 = 0.0 var n24_26 = 0.0 var n27_30 = 0.0 var n30L = 0.0 for exam in exams { switch exam.grade { case .passed: continue case .honors: n30L += 1 case .numerical(let numb): if numb >= 18 && numb <= 20 { n18_20 += 1 } else if numb >= 21 && numb <= 23 { n21_23 += 1 } else if numb >= 24 && numb <= 26 { n24_26 += 1 } else if numb >= 27 && numb <= 30 { n27_30 += 1 } } } var entries: [PieChartDataEntry] = [] var colors: [UIColor] = [] if n18_20 > 0 { entries.append(PieChartDataEntry(value: n18_20, label: "18~20")) colors.append(#colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1)) } if n21_23 > 0 { entries.append(PieChartDataEntry(value: n21_23, label: "21~23")) colors.append(#colorLiteral(red: 0.9568627477, green: 0.6588235497, blue: 0.5450980663, alpha: 1)) } if n24_26 > 0 { entries.append(PieChartDataEntry(value: n24_26, label: "24~26")) colors.append(#colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1)) } if n27_30 > 0 { entries.append(PieChartDataEntry(value: n27_30, label: "27~30")) colors.append(#colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1)) } if n30L > 0 { entries.append(PieChartDataEntry(value: n30L, label: "30L" )) colors.append(#colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)) } guard !(entries.isEmpty) else { return; } let set = PieChartDataSet(values: entries, label: nil) set.colors = colors let data = PieChartData(dataSet: set) let formatter = DefaultValueFormatter() formatter.decimals = 0 data.setValueFormatter(formatter) pieChartData = data pieChart?.data = data } }
gpl-3.0
7dbd4a36b98e3e9b90c14def11a60ef3
33.319759
159
0.595807
4.912349
false
false
false
false
garriguv/graphql-swift
Sources/language/Parser.swift
1
14213
import Foundation enum Keyword: String { case On = "on", Fragment = "fragment", BoolTrue = "true", BoolFalse = "false", Null = "null", Implements = "implements" case Type = "type", Interface = "interface", Union = "union", Scalar, EnumType = "enum", Input = "input", Extend = "extend" case Query = "query", Mutation = "mutation", Subscription = "subscription" } enum ParserError: ErrorType { case UnexpectedToken(Token) case UnexpectedKeyword(Keyword, Token) case WrongTokenKind(TokenKind, TokenKind) } public class Parser { private let lexer: Lexer private var token: Token! init(source: String) { lexer = Lexer(source: source) } public func parse() throws -> Document { token = try lexer.next() return try parseDocument() } } extension Parser { private func parseDocument() throws -> Document { var definitions: [Definition] = [] repeat { definitions.append(try parseDefinition()) } while try !skip(.EOF) return Document(definitions: definitions) } private func parseDefinition() throws -> Definition { if peek(.BraceL) { return .Operation(try parseOperationDefinition()) } guard peek(.Name), let value = token.value, keyword = Keyword(rawValue: value) else { throw ParserError.UnexpectedToken(token) } switch keyword { case .Query, .Mutation, .Subscription: return .Operation(try parseOperationDefinition()) case .Fragment: return .Fragment(try parseFragmentDefinition()) case .Type, .Interface, .Union, .Scalar, .EnumType, .Input: return .Type(try parseTypeDefinition()) case .Extend: return .TypeExtension(try parseTypeExtensionDefinition()) default: throw ParserError.UnexpectedToken(token) } } } extension Parser { private func parseOperationDefinition() throws -> OperationDefinition { if peek(.BraceL) { return OperationDefinition( type: .Query, name: nil, variableDefinitions: [], directives: [], selectionSet: try parseSelectionSet()) } let operationToken = try expect(.Name) guard let typeString = operationToken.value, type = OperationType(rawValue: typeString) else { throw ParserError.UnexpectedToken(operationToken) } let name: Name? = peek(.Name) ? try parseName() : nil return OperationDefinition( type: type, name: name, variableDefinitions: try parseVariableDefinitions(), directives: try parseDirectives(), selectionSet: try parseSelectionSet()) } private func parseVariableDefinitions() throws -> [VariableDefinition] { return peek(.ParenL) ? try many(openKind: .ParenL, parseFn: parseVariableDefinition, closeKind: .ParenR) : [] } private func parseVariableDefinition() throws -> VariableDefinition { let variable = try parseVariable() try expect(.Colon) let type = try parseType() let defaultValue: Value? = try skip(.Equals) ? try parseValueLiteral(isConst: true) : nil return VariableDefinition(variable: variable, type: type, defaultValue: defaultValue) } private func parseVariable() throws -> Variable { try expect(.Dollar) return Variable(name: try parseName()) } private func parseSelectionSet() throws -> SelectionSet { return SelectionSet(selections: try many(openKind: .BraceL, parseFn: parseSelection, closeKind: .BraceR)) } private func parseSelection() throws -> Selection { return peek(.Spread) ? try parseFragment() : Selection.FieldSelection(try parseField()) } private func parseField() throws -> Field { let nameOrAlias = try parseName() let alias: Name? let name: Name if try skip(.Colon) { alias = nameOrAlias name = try parseName() } else { alias = nil name = nameOrAlias } return Field( alias: alias, name: name, arguments: try parseArguments(), directives: try parseDirectives(), selectionSet: peek(.BraceL) ? try parseSelectionSet() : nil) } private func parseArguments() throws -> [Argument] { return peek(.ParenL) ? try many(openKind: .ParenL, parseFn: parseArgument, closeKind: .ParenR) : [] } private func parseArgument() throws -> Argument { let name = try parseName() try expect(.Colon) let value = try parseValueLiteral(isConst: false) return Argument(name: name, value: value) } private func parseName() throws -> Name { let nameToken = try expect(.Name) return Name(value: nameToken.value) } } extension Parser { private func parseFragment() throws -> Selection { try expect(.Spread) if peek(.Name) && token.value != Keyword.On.rawValue { return .FragmentSpreadSelection(FragmentSpread( name: try parseFragmentName(), directives: try parseDirectives())) } let typeCondition: Type? if token.value == Keyword.On.rawValue { try advance() typeCondition = try parseNamedType() } else { typeCondition = nil } return .InlineFragmentSelection(InlineFragment( typeCondition: typeCondition, directives: try parseDirectives(), selectionSet: try parseSelectionSet())) } private func parseFragmentDefinition() throws -> FragmentDefinition { try expectKeyword(.Fragment) let name = try parseFragmentName() try expectKeyword(.On) let typeCondition = try parseNamedType() return FragmentDefinition( name: name, typeCondition: typeCondition, directives: try parseDirectives(), selectionSet: try parseSelectionSet() ) } private func parseFragmentName() throws -> Name { if token.value == Keyword.On.rawValue { throw ParserError.UnexpectedToken(token) } return try parseName() } } extension Parser { private func parseValueLiteral(isConst isConst: Bool) throws -> Value { switch token.kind { case .BracketL: return try parseList(isConst: isConst) case .BraceL: return try parseObject(isConst: isConst) case .Int: guard let value = token.value else { throw ParserError.UnexpectedToken(token) } try advance() return .IntValue(value) case .Float: guard let value = token.value else { throw ParserError.UnexpectedToken(token) } try advance() return .FloatValue(value) case .String: guard let value = token.value else { throw ParserError.UnexpectedToken(token) } try advance() return .StringValue(value) case .Name: if let value = token.value where (value == Keyword.BoolFalse.rawValue || value == Keyword.BoolTrue.rawValue) { try advance() return .BoolValue(value) } else if token.value != Keyword.Null.rawValue { guard let value = token.value else { throw ParserError.UnexpectedToken(token) } try advance() return .Enum(value) } case .Dollar: if !isConst { return .VariableValue(try parseVariable()) } default: throw ParserError.UnexpectedToken(token) } throw ParserError.UnexpectedToken(token) } private func parseList(isConst isConst: Bool) throws -> Value { return .List(try any(openKind: .BracketL, parseFn: { return try self.parseValueLiteral(isConst: isConst) }, closeKind: .BracketR)) } private func parseObject(isConst isConst: Bool) throws -> Value { try expect(.BraceL) var fields: [ObjectField] = [] while try !skip(.BraceR) { fields.append(try parseObjectField(isConst: isConst)) } return .Object(fields) } private func parseObjectField(isConst isConst: Bool) throws -> ObjectField { let name = try parseName() try expect(.Colon) let value = try parseValueLiteral(isConst: isConst) return ObjectField(name: name, value: value) } } extension Parser { private func parseDirectives() throws -> [Directive] { var directives: [Directive] = [] while peek(.At) { directives.append(try parseDirective()) } return directives } private func parseDirective() throws -> Directive { try expect(.At) return Directive(name: try parseName(), arguments: try parseArguments()) } } extension Parser { private func parseType() throws -> Type { let type: Type if try skip(.BracketL) { let listType = try parseType() try expect(.BracketR) type = .List(listType) } else { type = try parseNamedType() } if try skip(.Bang) { return .NonNull(type) } return type } private func parseNamedType() throws -> Type { return .Named(try parseName()) } } extension Parser { private func parseTypeDefinition() throws -> TypeDefinition { if !peek(.Name) { throw ParserError.UnexpectedToken(token) } guard let value = token.value, type = Keyword(rawValue: value) else { throw ParserError.UnexpectedToken(token) } switch type { case .Type: return .Object(try parseObjectTypeDefinition()) case .Interface: return .Interface(try parseInterfaceTypeDefinition()) case .Union: return .Union(try parseUnionTypeDefinition()) case .Scalar: return .Scalar(try parseScalarTypeDefinition()) case .EnumType: return .Enum(try parseEnumTypeDefinition()) case .Input: return .InputObject(try parseInputObjectTypeDefinition()) default: throw ParserError.UnexpectedToken(token) } } private func parseObjectTypeDefinition() throws -> ObjectTypeDefinition { try expectKeyword(.Type) return ObjectTypeDefinition( name: try parseName(), interfaces: try parseImplementsInterfaces(), fields: try any(openKind: .BraceL, parseFn: parseFieldDefinition, closeKind: .BraceR)) } private func parseImplementsInterfaces() throws -> [Type] { if token.value == Keyword.Implements.rawValue { try advance() var types: [Type] = [] repeat { types.append(try parseNamedType()) } while !peek(.BraceL) return types } return [] } private func parseFieldDefinition() throws -> FieldDefinition { let name = try parseName() let arguments = try parseArgumentDefinitions() try expect(.Colon) let type = try parseType() return FieldDefinition(name: name, arguments: arguments, type: type) } private func parseArgumentDefinitions() throws -> [InputValueDefinition] { if peek(.ParenL) { return try many(openKind: .ParenL, parseFn: parseInputValueDefinition, closeKind: .ParenR) } return [] } private func parseInputValueDefinition() throws -> InputValueDefinition { let name = try parseName() try expect(.Colon) let type = try parseType() let defaultValue: Value? = try skip(.Equals) ? try parseValueLiteral(isConst: true) : nil return InputValueDefinition(name: name, type: type, defaultValue: defaultValue) } private func parseInterfaceTypeDefinition() throws -> InterfaceTypeDefinition { try expectKeyword(.Interface) return InterfaceTypeDefinition( name: try parseName(), fields: try any(openKind: .BraceL, parseFn: parseFieldDefinition, closeKind: .BraceR)) } private func parseUnionTypeDefinition() throws -> UnionTypeDefinition { try expectKeyword(.Union) let name = try parseName() try expect(.Equals) let types = try parseUnionMembers() return UnionTypeDefinition(name: name, types: types) } private func parseUnionMembers() throws -> [Type] { var members: [Type] = [] repeat { members.append(try parseNamedType()) } while try skip(.Pipe) return members } private func parseScalarTypeDefinition() throws -> ScalarTypeDefinition { try expectKeyword(.Scalar) return ScalarTypeDefinition(name: try parseName()) } private func parseEnumTypeDefinition() throws -> EnumTypeDefinition { try expectKeyword(.EnumType) return EnumTypeDefinition( name: try parseName(), values: try many(openKind: .BraceL, parseFn: parseEnumValueDefinition, closeKind: .BraceR)) } private func parseEnumValueDefinition() throws -> EnumValueDefinition { return EnumValueDefinition(name: try parseName()) } private func parseInputObjectTypeDefinition() throws -> InputObjectTypeDefinition { try expectKeyword(.Input) return InputObjectTypeDefinition( name: try parseName(), fields: try any(openKind: .BraceL, parseFn: parseInputValueDefinition, closeKind: .BraceR)) } private func parseTypeExtensionDefinition() throws -> TypeExtensionDefinition { try expectKeyword(.Extend) return TypeExtensionDefinition(definition: try parseObjectTypeDefinition()) } } extension Parser { private func advance() throws { token = try lexer.next() } private func skip(kind: TokenKind) throws -> Bool { let match = token.kind == kind if match { try advance() } return match } private func peek(kind: TokenKind) -> Bool { return token.kind == kind } private func expect(kind: TokenKind) throws -> Token { let currentToken = token if currentToken.kind == kind { try advance() return currentToken } throw ParserError.WrongTokenKind(kind, currentToken.kind) } private func expectKeyword(keyword: Keyword) throws -> Token { let currentToken = token if token.kind == .Name && token.value == keyword.rawValue { try advance() return currentToken } throw ParserError.UnexpectedKeyword(keyword, currentToken) } private func any<T>(openKind openKind: TokenKind, parseFn: () throws -> T, closeKind: TokenKind) throws -> [T] { try expect(openKind) var nodes: [T] = [] while try !skip(closeKind) { nodes.append(try parseFn()) } return nodes } private func many<T>(openKind openKind: TokenKind, parseFn: () throws -> T, closeKind: TokenKind) throws -> [T] { try expect(openKind) var nodes = [try parseFn()] while try !skip(closeKind) { nodes.append(try parseFn()) } return nodes } } extension Parser { private func syntaxError(token: Token) throws { throw ParserError.UnexpectedToken(token) } }
mit
30c8326e5432c9b2d41b866298d0b4f3
27.369261
134
0.672905
4.413975
false
false
false
false
obrichak/discounts
discounts/Classes/DAO/DataObjects/CompanyObject/CompanyObject.swift
1
373
// // CompanyObject.swift // discounts // // Created by Alexandr Chernyy on 9/15/14. // Copyright (c) 2014 Alexandr Chernyy. All rights reserved. // import Foundation class CompanyObject { var companyId:Int = 0 var categoryId:Int = 0 var companyName:String = "" var discount:String = "" var imageName:String = "" var discountCode:String = "" }
gpl-3.0
cfa28152a49d9f5fab8d922a8fb480b1
19.777778
61
0.662198
3.73
false
false
false
false
natecook1000/swift
stdlib/public/SDK/Foundation/NSArray.swift
2
5307
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module //===----------------------------------------------------------------------===// // Arrays //===----------------------------------------------------------------------===// extension NSArray : ExpressibleByArrayLiteral { /// Create an instance initialized with `elements`. public required convenience init(arrayLiteral elements: Any...) { // Let bridging take care of it. self.init(array: elements) } } extension Array : _ObjectiveCBridgeable { /// Private initializer used for bridging. /// /// The provided `NSArray` will be copied to ensure that the copy can /// not be mutated by other code. internal init(_cocoaArray: NSArray) { assert(_isBridgedVerbatimToObjectiveC(Element.self), "Array can be backed by NSArray only when the element type can be bridged verbatim to Objective-C") // FIXME: We would like to call CFArrayCreateCopy() to avoid doing an // objc_msgSend() for instances of CoreFoundation types. We can't do that // today because CFArrayCreateCopy() copies array contents unconditionally, // resulting in O(n) copies even for immutable arrays. // // <rdar://problem/19773555> CFArrayCreateCopy() is >10x slower than // -[NSArray copyWithZone:] // // The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS // and watchOS. self = Array( _immutableCocoaArray: unsafeBitCast(_cocoaArray.copy() as AnyObject, to: _NSArrayCore.self)) } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSArray { return unsafeBitCast(self._bridgeToObjectiveCImpl(), to: NSArray.self) } public static func _forceBridgeFromObjectiveC( _ source: NSArray, result: inout Array? ) { // If we have the appropriate native storage already, just adopt it. if let native = Array._bridgeFromObjectiveCAdoptingNativeStorageOf(source) { result = native return } if _fastPath(_isBridgedVerbatimToObjectiveC(Element.self)) { // Forced down-cast (possible deferred type-checking) result = Array(_cocoaArray: source) return } result = _arrayForceCast([AnyObject](_cocoaArray: source)) } public static func _conditionallyBridgeFromObjectiveC( _ source: NSArray, result: inout Array? ) -> Bool { // Construct the result array by conditionally bridging each element. let anyObjectArr = [AnyObject](_cocoaArray: source) result = _arrayConditionalCast(anyObjectArr) return result != nil } public static func _unconditionallyBridgeFromObjectiveC( _ source: NSArray? ) -> Array { // `nil` has historically been used as a stand-in for an empty // array; map it to an empty array instead of failing. if _slowPath(source == nil) { return Array() } // If we have the appropriate native storage already, just adopt it. if let native = Array._bridgeFromObjectiveCAdoptingNativeStorageOf(source!) { return native } if _fastPath(_isBridgedVerbatimToObjectiveC(Element.self)) { // Forced down-cast (possible deferred type-checking) return Array(_cocoaArray: source!) } return _arrayForceCast([AnyObject](_cocoaArray: source!)) } } extension NSArray : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self as! Array<AnyHashable>) } } extension NSArray : Sequence { /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). final public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } /* TODO: API review extension NSArray : Swift.Collection { final public var startIndex: Int { return 0 } final public var endIndex: Int { return count } } */ extension NSArray { // Overlay: - (instancetype)initWithObjects:(id)firstObj, ... public convenience init(objects elements: Any...) { self.init(array: elements) } } extension NSArray { /// Initializes a newly allocated array by placing in it the objects /// contained in a given array. /// /// - Returns: An array initialized to contain the objects in /// `anArray``. The returned object might be different than the /// original receiver. /// /// Discussion: After an immutable array has been initialized in /// this way, it cannot be modified. @nonobjc public convenience init(array anArray: NSArray) { self.init(array: anArray as Array) } } extension NSArray : CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self as [AnyObject]) } } extension Array: CVarArg {}
apache-2.0
bb184ceee479abd2662d11050491d8f2
30.778443
105
0.6531
4.772482
false
false
false
false
kstaring/swift
test/decl/enum/objc_enum_multi_file.swift
4
2040
// RUN: not %target-swift-frontend -module-name main %s -primary-file %S/Inputs/objc_enum_multi_file_helper.swift -parse -D NO_RAW_TYPE 2>&1 | %FileCheck -check-prefix=NO_RAW_TYPE %s // RUN: not %target-swift-frontend -module-name main %s -primary-file %S/Inputs/objc_enum_multi_file_helper.swift -parse -D BAD_RAW_TYPE 2>&1 | %FileCheck -check-prefix=BAD_RAW_TYPE %s // RUN: not %target-swift-frontend -module-name main %s -primary-file %S/Inputs/objc_enum_multi_file_helper.swift -parse -D NON_INT_RAW_TYPE 2>&1 | %FileCheck -check-prefix=NON_INT_RAW_TYPE %s // RUN: not %target-swift-frontend -module-name main %s -primary-file %S/Inputs/objc_enum_multi_file_helper.swift -parse -D NO_CASES 2>&1 | %FileCheck -check-prefix=NO_CASES %s // RUN: not %target-swift-frontend -module-name main %s -primary-file %S/Inputs/objc_enum_multi_file_helper.swift -parse -D DUPLICATE_CASES 2>&1 | %FileCheck -check-prefix=DUPLICATE_CASES %s // Note that the *other* file is the primary file in this test! #if NO_RAW_TYPE // NO_RAW_TYPE: :[[@LINE+1]]:12: error: '@objc' enum must declare an integer raw type @objc enum TheEnum { case A } #elseif BAD_RAW_TYPE // BAD_RAW_TYPE: :[[@LINE+1]]:22: error: '@objc' enum raw type 'Array<Int>' is not an integer type @objc enum TheEnum : Array<Int> { case A } #elseif NON_INT_RAW_TYPE // NON_INT_RAW_TYPE: :[[@LINE+1]]:22: error: '@objc' enum raw type 'Float' is not an integer type @objc enum TheEnum : Float { case A = 0.0 } #elseif NO_CASES // NO_CASES: :[[@LINE+1]]:22: error: an enum with no cases cannot declare a raw type @objc enum TheEnum : Int32 { static var A: TheEnum! { return nil } } #elseif DUPLICATE_CASES @objc enum TheEnum : Int32 { case A case B = 0 // DUPLICATE_CASES: :[[@LINE-1]]:12: error: raw value for enum case is not unique // DUPLICATE_CASES: :[[@LINE-3]]:8: note: raw value previously used here // DUPLICATE_CASES: :[[@LINE-4]]:8: note: raw value implicitly auto-incremented from zero } #else enum TheEnum: Invalid { // should never be hit case A } #endif
apache-2.0
38b81b839353bd7bd3bb54aa0307bed4
43.347826
192
0.694118
2.973761
false
false
false
false
yichizhang/JCTiledScrollView_Swift
Demo/Demo-Swift/Demo-Swift/ViewController.swift
1
7534
// // Copyright (c) 2015-present Yichi Zhang // https://github.com/yichizhang // [email protected] // // This source code is licensed under MIT license found in the LICENSE file // in the root directory of this source tree. // Attribution can be found in the ATTRIBUTION file in the root directory // of this source tree. // import UIKit enum JCDemoType { case PDF case Image } let SkippingGirlImageName = "SkippingGirl" let SkippingGirlImageSize = CGSize(width: 432, height: 648) let ButtonTitleCancel = "Cancel" let ButtonTitleRemoveAnnotation = "Remove this Annotation" @objc class ViewController: UIViewController, JCTiledScrollViewDelegate, JCTileSource, UIAlertViewDelegate { let demoAnnotationViewReuseID = "DemoAnnotationView" var scrollView: JCTiledScrollView! var infoLabel: UILabel! var searchField: UITextField! var mode: JCDemoType! weak var selectedAnnotation: JCAnnotation? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if (mode == JCDemoType.PDF) { scrollView = JCTiledPDFScrollView( frame: self.view.bounds, URL: Bundle.main.url(forResource: "Map", withExtension: "pdf")! ) } else { scrollView = JCTiledScrollView(frame: self.view.bounds, contentSize: SkippingGirlImageSize) } scrollView.tiledScrollViewDelegate = self scrollView.zoomScale = 1.0 scrollView.dataSource = self scrollView.tiledScrollViewDelegate = self scrollView.tiledView.shouldAnnotateRect = true // totals 4 sets of tiles across all devices, retina devices will miss out on the first 1x set scrollView.levelsOfZoom = 3 scrollView.levelsOfDetail = 3 scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) infoLabel = UILabel(frame: .zero) infoLabel.backgroundColor = UIColor.black infoLabel.textColor = UIColor.white infoLabel.textAlignment = NSTextAlignment.center infoLabel.translatesAutoresizingMaskIntoConstraints = false view.addSubview(infoLabel) view.addConstraints([ NSLayoutConstraint(item: scrollView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1, constant: 0), NSLayoutConstraint(item: scrollView, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1, constant: 0), NSLayoutConstraint(item: scrollView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: scrollView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0), NSLayoutConstraint(item: infoLabel, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 20), NSLayoutConstraint(item: infoLabel, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0), ]) addRandomAnnotations() scrollView.refreshAnnotations() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func addRandomAnnotations() { for number in 0 ... 8 { let annotation = DemoAnnotation(isSelectable: (number % 3 != 0)) let w = UInt32(UInt(scrollView.tiledView.bounds.width)) let h = UInt32(UInt(scrollView.tiledView.bounds.height)) annotation.contentPosition = CGPoint( x: CGFloat(UInt(arc4random_uniform(w))), y: CGFloat(UInt(arc4random_uniform(h))) ) scrollView.addAnnotation(annotation) } } // MARK: JCTiledScrollView Delegate func tiledScrollViewDidZoom(_ scrollView: JCTiledScrollView) { infoLabel.text = NSString(format: "zoomScale=%.2f", scrollView.zoomScale) as String } func tiledScrollView(_ scrollView: JCTiledScrollView, didReceiveSingleTap gestureRecognizer: UIGestureRecognizer) { let tapPoint: CGPoint = gestureRecognizer.location(in: scrollView.tiledView) infoLabel.text = NSString(format: "(%.2f, %.2f), zoomScale=%.2f", tapPoint.x, tapPoint.y, scrollView.zoomScale) as String } func tiledScrollView(_ scrollView: JCTiledScrollView, shouldSelectAnnotationView view: JCAnnotationView) -> Bool { if let annotation = view.annotation as? DemoAnnotation { return annotation.isSelectable } return true } func tiledScrollView(_ scrollView: JCTiledScrollView, didSelectAnnotationView view: JCAnnotationView) { guard let annotationView = view as? DemoAnnotationView, let annotation = annotationView.annotation as? DemoAnnotation else { return } let alertView = UIAlertView( title: "Annotation Selected", message: "You've selected an annotation. What would you like to do with it?", delegate: self, cancelButtonTitle: ButtonTitleCancel, otherButtonTitles: ButtonTitleRemoveAnnotation) alertView.show() selectedAnnotation = annotation annotation.isSelected = true annotationView.update(forAnnotation: annotation) } func tiledScrollView(_ scrollView: JCTiledScrollView, didDeselectAnnotationView view: JCAnnotationView) { guard let annotationView = view as? DemoAnnotationView, let annotation = annotationView.annotation as? DemoAnnotation else { return } selectedAnnotation = nil annotation.isSelected = false annotationView.update(forAnnotation: annotation) } func tiledScrollView(_ scrollView: JCTiledScrollView, viewForAnnotation annotation: JCAnnotation) -> JCAnnotationView { var annotationView: DemoAnnotationView! annotationView = (scrollView.dequeueReusableAnnotationViewWithReuseIdentifier(demoAnnotationViewReuseID) as? DemoAnnotationView) ?? DemoAnnotationView(frame: .zero, annotation: annotation, reuseIdentifier: demoAnnotationViewReuseID) annotationView.update(forAnnotation: annotation as? DemoAnnotation) return annotationView } func tiledScrollView(_ scrollView: JCTiledScrollView, imageForRow row: Int, column: Int, scale: Int) -> UIImage { let fileName = NSString(format: "%@_%dx_%d_%d.png", SkippingGirlImageName, scale, row, column) as String return UIImage(named: fileName)! } // MARK: UIAlertView Delegate func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) { guard let buttonTitle = alertView.buttonTitle(at: buttonIndex) else { return } switch buttonTitle { case ButtonTitleCancel: break case ButtonTitleRemoveAnnotation: if let selectedAnnotation = self.selectedAnnotation { scrollView.removeAnnotation(selectedAnnotation) } default: break } } }
mit
475e3dc23e360d5a234e256573a085be
36.859296
172
0.65888
5.163811
false
false
false
false
ReactiveCocoa/ReactiveSwift
ReactiveSwift.playground/Pages/Property.xcplaygroundpage/Contents.swift
1
9388
/*: > # IMPORTANT: To use `ReactiveSwift.playground`, please: 1. Retrieve the project dependencies using one of the following terminal commands from the ReactiveSwift project root directory: - `git submodule update --init` **OR**, if you have [Carthage](https://github.com/Carthage/Carthage) installed - `carthage checkout` 1. Open `ReactiveSwift.xcworkspace` 1. Build `ReactiveSwift-macOS` scheme 1. Finally open the `ReactiveSwift.playground` 1. Choose `View > Show Debug Area` */ import ReactiveSwift import Foundation /*: ## Property A **property**, represented by the [`PropertyProtocol`](https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/Sources/Property.swift) , stores a value and notifies observers about future changes to that value. - The current value of a property can be obtained from the `value` getter. - The `producer` getter returns a [signal producer](SignalProducer) that will send the property’s current value, followed by all changes over time. - The `signal` getter returns a [signal](Signal) that will send all changes over time, but not the initial value. */ scopedExample("Creation") { let mutableProperty = MutableProperty(1) // The value of the property can be accessed via its `value` attribute print("Property has initial value \(mutableProperty.value)") // The properties value can be observed via its `producer` or `signal attribute` // Note, how the `producer` immediately sends the initial value, but the `signal` only sends new values mutableProperty.producer.startWithValues { print("mutableProperty.producer received \($0)") } mutableProperty.signal.observeValues { print("mutableProperty.signal received \($0)") } print("---") print("Setting new value for mutableProperty: 2") mutableProperty.value = 2 print("---") // If a property should be exposed for readonly access, it can be wrapped in a Property let property = Property(mutableProperty) print("Reading value of readonly property: \(property.value)") property.signal.observeValues { print("property.signal received \($0)") } // Its not possible to set the value of a Property // readonlyProperty.value = 3 // But you can still change the value of the mutableProperty and observe its change on the property print("---") print("Setting new value for mutableProperty: 3") mutableProperty.value = 3 // Constant properties can be created by using the `Property(value:)` initializer let constant = Property(value: 1) // constant.value = 2 // The value of a constant property can not be changed } /*: ### Binding The `<~` operator can be used to bind properties in different ways. Note that in all cases, the target has to be a binding target, represented by the [`BindingTargetProvider`](https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/Sources/UnidirectionalBinding.swift). All mutable property types, represented by the [`MutablePropertyProtocol`](https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/Sources/Property.swift#L38), are inherently binding targets. * `property <~ signal` binds a [signal](Signal) to the property, updating the property’s value to the latest value sent by the signal. * `property <~ producer` starts the given [signal producer](SignalProducer), and binds the property’s value to the latest value sent on the started signal. * `property <~ otherProperty` binds one property to another, so that the destination property’s value is updated whenever the source property is updated. */ scopedExample("Binding from SignalProducer") { let producer = SignalProducer<Int, Never> { observer, _ in print("New subscription, starting operation") observer.send(value: 1) observer.send(value: 2) } let property = MutableProperty(0) property.producer.startWithValues { print("Property received \($0)") } // Notice how the producer will start the work as soon it is bound to the property property <~ producer } scopedExample("Binding from Signal") { let (signal, observer) = Signal<Int, Never>.pipe() let property = MutableProperty(0) property.producer.startWithValues { print("Property received \($0)") } property <~ signal print("Sending new value on signal: 1") observer.send(value: 1) print("Sending new value on signal: 2") observer.send(value: 2) } scopedExample("Binding from other Property") { let property = MutableProperty(0) property.producer.startWithValues { print("Property received \($0)") } let otherProperty = MutableProperty(0) // Notice how property receives another value of 0 as soon as the binding is established property <~ otherProperty print("Setting new value for otherProperty: 1") otherProperty.value = 1 print("Setting new value for otherProperty: 2") otherProperty.value = 2 } /*: ### Transformations Properties provide a number of transformations like `map`, `combineLatest` or `zip` for manipulation similar to [signal](Signal) and [signal producer](SignalProducer) */ scopedExample("`map`") { let property = MutableProperty(0) let mapped = property.map { $0 * 2 } mapped.producer.startWithValues { print("Mapped property received \($0)") } print("Setting new value for property: 1") property.value = 1 print("Setting new value for property: 2") property.value = 2 } scopedExample("`skipRepeats`") { let property = MutableProperty(0) let skipRepeatsProperty = property.skipRepeats() property.producer.startWithValues { print("Property received \($0)") } skipRepeatsProperty.producer.startWithValues { print("Skip-Repeats property received \($0)") } print("Setting new value for property: 0") property.value = 0 print("Setting new value for property: 1") property.value = 1 print("Setting new value for property: 1") property.value = 1 print("Setting new value for property: 0") property.value = 0 } scopedExample("`uniqueValues`") { let property = MutableProperty(0) let unique = property.uniqueValues() property.producer.startWithValues { print("Property received \($0)") } unique.producer.startWithValues { print("Unique values property received \($0)") } print("Setting new value for property: 0") property.value = 0 print("Setting new value for property: 1") property.value = 1 print("Setting new value for property: 1") property.value = 1 print("Setting new value for property: 0") property.value = 0 } scopedExample("`combineLatest`") { let propertyA = MutableProperty(0) let propertyB = MutableProperty("A") let combined = propertyA.combineLatest(with: propertyB) combined.producer.startWithValues { print("Combined property received \($0)") } print("Setting new value for propertyA: 1") propertyA.value = 1 print("Setting new value for propertyB: 'B'") propertyB.value = "B" print("Setting new value for propertyB: 'C'") propertyB.value = "C" print("Setting new value for propertyB: 'D'") propertyB.value = "D" print("Setting new value for propertyA: 2") propertyA.value = 2 } scopedExample("`zip`") { let propertyA = MutableProperty(0) let propertyB = MutableProperty("A") let zipped = propertyA.zip(with: propertyB) zipped.producer.startWithValues { print("Zipped property received \($0)") } print("Setting new value for propertyA: 1") propertyA.value = 1 print("Setting new value for propertyB: 'B'") propertyB.value = "B" // Observe that, in contrast to `combineLatest`, setting a new value for propertyB does not cause a new value for the zipped property until propertyA has a new value as well print("Setting new value for propertyB: 'C'") propertyB.value = "C" print("Setting new value for propertyB: 'D'") propertyB.value = "D" print("Setting new value for propertyA: 2") propertyA.value = 2 } scopedExample("`flatten`") { let property1 = MutableProperty("0") let property2 = MutableProperty("A") let property3 = MutableProperty("!") let property = MutableProperty(property1) // Try different merge strategies and see how the results change property.flatten(.latest).producer.startWithValues { print("Flattened property receive \($0)") } print("Sending new value on property1: 1") property1.value = "1" print("Sending new value on property: property2") property.value = property2 print("Sending new value on property1: 2") property1.value = "2" print("Sending new value on property2: B") property2.value = "B" print("Sending new value on property1: 3") property1.value = "3" print("Sending new value on property: property3") property.value = property3 print("Sending new value on property3: ?") property3.value = "?" print("Sending new value on property2: C") property2.value = "C" print("Sending new value on property1: 4") property1.value = "4" }
mit
cffc1f44ff5312e89574375eb0f8cdc9
33.612546
388
0.681557
4.479465
false
false
false
false
huangboju/Moots
算法学习/LeetCode/LeetCode/EvalRPN.swift
1
989
// // EvalRPN.swift // LeetCode // // Created by 黄伯驹 on 2019/9/21. // Copyright © 2019 伯驹 黄. All rights reserved. // import Foundation // 逆波兰表达式 // https://zh.wikipedia.org/wiki/%E9%80%86%E6%B3%A2%E5%85%B0%E8%A1%A8%E7%A4%BA%E6%B3%95 // https://www.jianshu.com/p/f2c88d983ff5 func evalRPN(_ tokens: [String]) -> Int { let operators: Set<String> = ["*","+","/","-"] var stack = Array<Int>() for token in tokens { if operators.contains(token) { let num1 = stack.removeLast() let index = stack.count - 1 switch token { case "*": stack[index] *= num1 case "-": stack[index] -= num1 case "+": stack[index] += num1 case "/": stack[index] /= num1 default: break } continue } stack.append(Int(token)!) } return stack[0] }
mit
8a67b0fcabf63b7cedf0c6543e3c180b
23.717949
87
0.481328
3.370629
false
false
false
false
vanshg/MacAssistant
Pods/Magnet/Lib/Magnet/KeyCombo.swift
1
3115
// // KeyCombo.swift // Magnet // // Created by 古林俊佑 on 2016/03/09. // Copyright © 2016年 Shunsuke Furubayashi. All rights reserved. // import Cocoa import Carbon public final class KeyCombo: NSObject, NSCopying, NSCoding, Codable { // MARK: - Properties public let keyCode: Int public let modifiers: Int public let doubledModifiers: Bool public var characters: String { if doubledModifiers { return "" } return KeyCodeTransformer.shared.transformValue(keyCode, carbonModifiers: modifiers) } // MARK: - Initialize public init?(keyCode: Int, carbonModifiers: Int) { if keyCode < 0 || carbonModifiers < 0 { return nil } if KeyTransformer.containsFunctionKey(keyCode) { self.modifiers = Int(UInt(carbonModifiers) | NSEvent.ModifierFlags.function.rawValue) } else { self.modifiers = carbonModifiers } self.keyCode = keyCode self.doubledModifiers = false } public init?(keyCode: Int, cocoaModifiers: NSEvent.ModifierFlags) { if keyCode < 0 || !KeyTransformer.supportedCocoaFlags(cocoaModifiers) { return nil } if KeyTransformer.containsFunctionKey(keyCode) { self.modifiers = Int(UInt(KeyTransformer.carbonFlags(from: cocoaModifiers)) | NSEvent.ModifierFlags.function.rawValue) } else { self.modifiers = KeyTransformer.carbonFlags(from: cocoaModifiers) } self.keyCode = keyCode self.doubledModifiers = false } public init?(doubledCarbonModifiers modifiers: Int) { if !KeyTransformer.singleCarbonFlags(modifiers) { return nil } self.keyCode = 0 self.modifiers = modifiers self.doubledModifiers = true } public init?(doubledCocoaModifiers modifiers: NSEvent.ModifierFlags) { if !KeyTransformer.singleCocoaFlags(modifiers) { return nil } self.keyCode = 0 self.modifiers = KeyTransformer.carbonFlags(from: modifiers) self.doubledModifiers = true } public func copy(with zone: NSZone?) -> Any { if doubledModifiers { return KeyCombo(doubledCarbonModifiers: modifiers)! } else { return KeyCombo(keyCode: keyCode, carbonModifiers: modifiers)! } } public init?(coder aDecoder: NSCoder) { self.keyCode = aDecoder.decodeInteger(forKey: "keyCode") self.modifiers = aDecoder.decodeInteger(forKey: "modifiers") self.doubledModifiers = aDecoder.decodeBool(forKey: "doubledModifiers") } public func encode(with aCoder: NSCoder) { aCoder.encode(keyCode, forKey: "keyCode") aCoder.encode(modifiers, forKey: "modifiers") aCoder.encode(doubledModifiers, forKey: "doubledModifiers") } // MARK: - Equatable public override func isEqual(_ object: Any?) -> Bool { guard let keyCombo = object as? KeyCombo else { return false } return keyCode == keyCombo.keyCode && modifiers == keyCombo.modifiers && doubledModifiers == keyCombo.doubledModifiers } }
mit
5b62716e0a693b3ac7139cd3990eb43b
33.10989
130
0.658505
4.775385
false
false
false
false
ziaukhan/Swift-Big-Nerd-Ranch-Guide
chapter 6/Chap6/Chap6/BNRHypnosisView.swift
1
2729
// // BNRHypnosisView.swift // Chap4 // import UIKit class BNRHypnosisView: UIView { override init(frame: CGRect) { super.init(frame: frame) // Initialization code //All BNRHyponosisView starts with a clear background Color self.backgroundColor = UIColor.clearColor() var circleColor:UIColor = UIColor.lightGrayColor() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } var circleColor:UIColor = UIColor.lightGrayColor() override func drawRect(rect: CGRect) { var bounds = self.bounds //figure out the center of the bounds rectangle var center = CGPoint() center.x = (bounds.origin.x + bounds.size.width) / 2.0 center.y = (bounds.origin.y + bounds.size.height) / 2.0 /*//The circle will be the largest that will fit in the view var radius:CGFloat = hypot(bounds.size.width, bounds.size.height)/4.0 */ var path = UIBezierPath() /*//Add an arc to the path at center, with radius of radius, //from 0 to 2*PI randian (a circle) var startAngle:CGFloat = 0.0 path.addArcWithCenter(center, radius: radius, startAngle: startAngle, endAngle: Float(M_PI)*2.0, clockwise: true) */ var maxRadius = hypot(bounds.size.width, bounds.size.height)/2.0 for(var currentRadius = maxRadius; currentRadius > 0; currentRadius -= 20){ path.moveToPoint(CGPointMake(center.x + currentRadius, center.y)) var startAngle:CGFloat = 0.0 path.addArcWithCenter(center, radius:currentRadius, // Note this is currentRadius! startAngle: startAngle, endAngle: CGFloat(M_PI)*2.0, clockwise: true) } ///Congigure line width to 10 points path.lineWidth = 10 //Configure the drawing color to light gray self.circleColor.setStroke() //draw the line path.stroke() // --- END CHAPTER # 4 // } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { //get 3 random number b/w 0 and 1 var red:CGFloat = CGFloat(Float(arc4random()) % 100.0) / 100.0 var greenn:CGFloat = CGFloat(Float(arc4random()) % 100.0) / 100.0 var blue:CGFloat = CGFloat(Float(arc4random()) % 100.0) / 100.0 var randomColor = UIColor(red: red, green: greenn, blue: blue, alpha: 1.0) self.circleColor = randomColor self.setNeedsDisplay() } }
apache-2.0
f0c3fb15e07666c36c7deb2c3f602249
29.662921
121
0.574569
4.380417
false
false
false
false
noppoMan/aws-sdk-swift
CodeGenerator/Sources/CodeGenerator/Glob.swift
1
1028
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Darwin.C import Foundation public class Glob { public static func entries(pattern: String) -> [String] { var files = [String]() var gt = glob_t() let res = glob(pattern.cString(using: .utf8)!, 0, nil, &gt) if res != 0 { return files } for i in 0..<gt.gl_pathc { let x = gt.gl_pathv[Int(i)] let c = UnsafePointer<CChar>(x)! let s = String(cString: c) files.append(s) } globfree(&gt) return files } }
apache-2.0
dcb62993c4016bba8ad5d8db47d9598f
26.783784
80
0.490272
4.355932
false
false
false
false
jpush/jchat-swift
JChat/Src/ChatModule/Input/InputView/Emoticon/JCEmoticonLine.swift
1
2742
// // JCEmoticonLine.swift // JChat // // Created by JIGUANG on 2017/3/9. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit internal class JCEmoticonLine { func draw(in ctx: CGContext) { _ = emoticons.reduce(CGRect(origin: vaildRect.origin, size: itemSize)) { $1.draw(in: $0, in: ctx) return $0.offsetBy(dx: $0.width + minimumInteritemSpacing, dy: 0) } } func rect(at index: Int) -> CGRect? { guard index < emoticons.count else { return nil } let isp = minimumInteritemSpacing let nwidth = (itemSize.width + isp) * CGFloat(index) return CGRect(origin: CGPoint(x: vaildRect.minX + nwidth, y: vaildRect.minY), size: itemSize) } func addEmoticon(_ emoticon: JCEmoticon) -> Bool { let isp = minimumInteritemSpacing let nwidth = visableSize.width + isp + itemSize.width let nwidthWithDelete = visableSize.width + (isp + itemSize.width) * 2 let nheight = max(visableSize.height, itemSize.height) if floor(vaildRect.minX + nwidth) > floor(vaildRect.maxX) { return false } if itemType.isSmall && isLastLine && floor(vaildRect.minX + nwidthWithDelete) > floor(vaildRect.maxX) { return false } if floor(vaildRect.minY + nheight) > floor(vaildRect.maxY) { return false } if visableSize.height != nheight { _isLastLine = nil } visableSize.width = nwidth visableSize.height = nheight emoticons.append(emoticon) return true } var itemSize: CGSize var vaildRect: CGRect var visableSize: CGSize var itemType: JCEmoticonType var isLastLine: Bool { if let isLastLine = _isLastLine { return isLastLine } let isLastLine = floor(vaildRect.minY + visableSize.height + minimumLineSpacing + itemSize.height) > floor(vaildRect.maxY) _isLastLine = isLastLine return isLastLine } var minimumLineSpacing: CGFloat var minimumInteritemSpacing: CGFloat var emoticons: [JCEmoticon] var _isLastLine: Bool? init(_ first: JCEmoticon, _ itemSize: CGSize, _ rect: CGRect, _ lineSpacing: CGFloat, _ interitemSpacing: CGFloat, _ itemType: JCEmoticonType) { self.itemSize = itemSize self.itemType = itemType self.vaildRect = rect self.visableSize = itemSize minimumLineSpacing = lineSpacing minimumInteritemSpacing = interitemSpacing emoticons = [first] } }
mit
b1d727cc1bcc6e1a734d7890bae2b0af
28.138298
130
0.591092
4.347619
false
false
false
false
alessioros/mobilecodegenerator3
examples/BookShelf/ios/completed/BookShelf/BookShelf/AppDelegate.swift
1
4411
import UIKit import CoreData import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // Configure Firebase FirebaseApp.configure() 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:. } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "BookShelf") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
gpl-3.0
81380ef425659f23914d5ae690a349ac
51.511905
285
0.682612
6.0342
false
false
false
false
RomainBoulay/SectionSpacingFlowLayout
CollectionViewCompactLayout/SectionPosition.swift
1
1690
import Foundation import UIKit struct SectionAttribute { let initialMinY: CGFloat let initialMaxY: CGFloat let itemsCount: Int private let spacingHeight: CGFloat private let previousAggregatedVerticalOffset: CGFloat init(minY: CGFloat, maxY: CGFloat, itemsCount: Int, spacingHeight: CGFloat, previousAggregatedVerticalOffset: CGFloat ) { self.initialMinY = minY self.initialMaxY = maxY self.itemsCount = itemsCount self.spacingHeight = spacingHeight self.previousAggregatedVerticalOffset = previousAggregatedVerticalOffset } static func empty(previousAggregatedVerticalOffset: CGFloat, sectionTopHeight: CGFloat, sectionBottomHeight: CGFloat) -> SectionAttribute { let verticalOffsetMinusHeaderFooter = previousAggregatedVerticalOffset - sectionTopHeight - sectionBottomHeight return SectionAttribute(minY: .nan, maxY: .nan, itemsCount: 0, spacingHeight: 0, previousAggregatedVerticalOffset: verticalOffsetMinusHeaderFooter) } var hasItems: Bool { return itemsCount > 0 } var aggregatedVerticalOffset: CGFloat { return previousAggregatedVerticalOffset + spacingHeight } var decorationViewMinY: CGFloat { return initialMinY + previousAggregatedVerticalOffset } var newMinY: CGFloat { return initialMinY + aggregatedVerticalOffset } var newMaxY: CGFloat { return initialMaxY + aggregatedVerticalOffset } }
mit
e464ebec80a34358a75b409dd425558b
30.296296
119
0.649704
5.909091
false
false
false
false
WTGrim/WTOfo_Swift
Ofo_Swift/Ofo_Swift/MoreViewController.swift
1
785
// // MoreViewController.swift // Ofo_Swift // // Created by Dwt on 2017/9/22. // Copyright © 2017年 Dwt. All rights reserved. // import UIKit import WebKit class MoreViewController: UIViewController , WKUIDelegate{ var webView : WKWebView! override func viewDidLoad() { super.viewDidLoad() title = "热门活动" let url = URL(string: "http://m.ofo.so/active.html")! let request = URLRequest(url: url as URL) webView = WKWebView(frame:CGRect(x:0, y:0, width:self.view.bounds.width, height:self.view.bounds.height)) webView.uiDelegate = self webView.load(request) view.addSubview(webView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
8c51d635e2a559d5830b15b470df1326
23.967742
113
0.642119
3.989691
false
false
false
false
iCrany/iOSExample
iOSExample/Module/TransitionExample/ViewController/Session4/Present/Error/VC/ErrorPresentFromViewController.swift
1
4069
// // ErrorPresentFromViewController.swift // iOSExample // // Created by iCrany on 2017/12/9. // Copyright © 2017 iCrany. All rights reserved. // import Foundation import UIKit class ErrorPresentFromViewController: UIViewController { fileprivate lazy var interactionController: SwipeUpInteractiveTransition = { let vc = PresentToViewController() let nav = UINavigationController(rootViewController: vc) let interaction = SwipeUpInteractiveTransition(startBlock: { [weak self] in guard let sSelf = self else { return } //Try1: 尝试 present 一个 UIViewController, 并且设置 vc.transitioningDelegate //结果:这个就是正常的 UIViewController 转场到 UIViewController, 交互手势正常 // vc.transitioningDelegate = sSelf // sSelf.present(vc, animated: true) //Try2: 尝试 present 一个 UINavigationController, 并且设置 UIViewController.transitioningDelegate //结果:这个是 UIViewController 转场到 UINavigationController 封装好的 UIViewController, 如果手势设置在 UIViewController.transitioningDelegate 上就交互手势就会失效 // vc.transitioningDelegate = sSelf // sSelf.present(nav, animated: true) //Try3: 尝试 present 一个 UINavigationController, 并且设置 UINavigationController.transitioningDelegate //结果:这个是 UIViewController 转场到 UINavigationController 封装好的 UIViewController, 如果手势设置在 UIViewController.transitioningDelegate 上,交互手势正常 nav.transitioningDelegate = sSelf sSelf.present(nav, animated: true) }, endBlock: { _ in }) return interaction }() fileprivate lazy var dismissAnimation: NormalDismissAnimation = { let dismissAnimation = NormalDismissAnimation() return dismissAnimation }() fileprivate lazy var presentAnimation: ErrorPresentAnimation = { let presentAnimation = ErrorPresentAnimation() return presentAnimation }() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init() { super.init(nibName: nil, bundle: nil) self.setupUI() } private func setupUI() { self.view.backgroundColor = .white let titleLabel = UILabel() titleLabel.text = "这里是 ErrorPresentFromViewController" self.view.addSubview(titleLabel) titleLabel.backgroundColor = .black titleLabel.textColor = .white titleLabel.snp.makeConstraints { maker in maker.center.equalToSuperview() maker.size.equalTo(CGSize(width: 200, height: 60)) } self.interactionController.writeToViewController(viewController: self) } } extension ErrorPresentFromViewController: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { //注意: 这里就是因为 PresentAnimation 中有检测是否是 UINavigationController, 如果是 UINavigationController 就是获取第一个 viewControllers 中的第一个 UIViewController, 导致交互动画的失效 return self.presentAnimation } //在 Session4 的例子中,dismiss 的动画如果不定义的话就是用系统默认的 // func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { // return self.dismissAnimation // } func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { let nowAnimator = animator as? NormalPresentAnimation guard nowAnimator != nil, self.interactionController.interacting else { return nil } return self.interactionController } }
mit
c83230945a9b45b86ffdcb5fe23abfe7
37.494845
170
0.706213
5.419448
false
false
false
false
Urinx/SublimeCode
Sublime/Sublime/SSHAddNewServerViewController.swift
1
5419
// // SSHAddNewServerViewController.swift // Sublime // // Created by Eular on 3/28/16. // Copyright © 2016 Eular. All rights reserved. // import UIKit import Gifu class SSHAddNewServerViewController: UITableViewController, UITextFieldDelegate { let settingList = [ ["ssh_server", "host"], ["ssh_port", "port"], ["ssh_user", "username"], ["ssh_password", "password"] ] var textFieldList = [UITextField]() override func viewDidLoad() { super.viewDidLoad() title = "New Server" tableView.backgroundColor = Constant.CapeCod tableView.separatorColor = Constant.TableCellSeparatorColor tableView.tableFooterView = UIView() Global.Notifi.addObserver(self, selector: #selector(self.keyboardDidShow), name: UIKeyboardDidShowNotification, object: nil) Global.Notifi.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIKeyboardDidHideNotification, object: nil) let header = UIView(frame: CGRectMake(0, 0, view.width, 80)) let gif = AnimatableImageView() gif.frame = CGRectMake(0, 20, view.width, 60) gif.contentMode = .ScaleAspectFit gif.animateWithImageData(NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("animation", ofType: "gif")!)!) gif.startAnimatingGIF() header.addSubview(gif) tableView.tableHeaderView = header } func keyboardDidShow() { navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "ssh_keyboard"), style: .Plain, target: self, action: #selector(self.dismissKeyboard)) } func keyboardWillHide() { navigationItem.rightBarButtonItem = nil } func dismissKeyboard() { self.view.endEditing(true) } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return [settingList.count, 1][section] } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 50 } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 0 } return Constant.FilesTableSectionHight } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { return nil } let headerView = UIView() headerView.frame = CGRectMake(0, 0, view.width, Constant.FilesTableSectionHight) headerView.backgroundColor = Constant.CapeCod return headerView } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .Default, reuseIdentifier: nil) cell.backgroundColor = Constant.NavigationBarAndTabBarColor cell.selectedBackgroundView = UIView(frame: cell.frame) cell.selectedBackgroundView?.backgroundColor = Constant.NavigationBarAndTabBarColor if indexPath.section == 0 { let tf = UITextField() tf.frame = CGRectMake(70, 3, cell.frame.width - 80, cell.frame.height) tf.attributedPlaceholder = NSAttributedString(string: settingList[indexPath.row][1], attributes: [NSForegroundColorAttributeName: UIColor.grayColor()]) tf.textColor = UIColor.whiteColor() tf.delegate = self if tf.placeholder == "port" { tf.keyboardType = .NumberPad } else if tf.placeholder == "host" { tf.keyboardType = .URL } tf.autocorrectionType = .No tf.autocapitalizationType = .None cell.addSubview(tf) cell.imageView?.image = UIImage(named: settingList[indexPath.row][0]) textFieldList.append(tf) } else { let doneImg = UIImageView() doneImg.frame = CGRectMake(0, 0, 40, 40) doneImg.image = UIImage(named: "ssh_done") cell.addSubview(doneImg) doneImg.atCenter() } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.section == 1 { var serverInfo = [String:String]() for tf in textFieldList { if tf.text!.isEmpty { view.Toast(message: "\(tf.placeholder!) can't be empty", hasNavigationBar: true) return } else { serverInfo[tf.placeholder!] = tf.text } } let serverPlist = Plist(path: Constant.SublimeRoot+"/etc/ssh_list.plist") do { try serverPlist.appendToPlistFile(serverInfo) navigationController?.popViewControllerAnimated(true) } catch { view.Toast(message: "Save failed!", hasNavigationBar: true) } } } }
gpl-3.0
e9abe6839e98a6001a72a52be79db9b7
37.7
168
0.626061
5.164919
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureCoin/Sources/FeatureCoinDomain/Localization/LocalizationConstants+CoinDomain.swift
1
4199
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization extension LocalizationConstants { enum CoinDomain { enum Button { enum Title { enum Rewards { static let summary = NSLocalizedString( "Summary", comment: "Account Actions: Rewards summary CTA title" ) } static let buy = NSLocalizedString( "Buy", comment: "Account Actions: Buy CTA title" ) static let sell = NSLocalizedString( "Sell", comment: "Account Actions: Sell CTA title" ) static let send = NSLocalizedString( "Send", comment: "Account Actions: Send CTA title" ) static let receive = NSLocalizedString( "Receive", comment: "Account Actions: Receive CTA title" ) static let swap = NSLocalizedString( "Swap", comment: "Account Actions: Swap CTA title" ) static let activity = NSLocalizedString( "Activity", comment: "Account Actions: Activity CTA title" ) static let withdraw = NSLocalizedString( "Withdraw", comment: "Account Actions: Withdraw CTA title" ) static let deposit = NSLocalizedString( "Deposit", comment: "Account Actions: Deposit CTA title" ) } enum Description { enum Rewards { static let summary = NSLocalizedString( "View Accrued %@ Rewards", comment: "Account Actions: Rewards summary CTA description" ) static let withdraw = NSLocalizedString( "Withdraw %@ from Rewards Account", comment: "Account Actions: Rewards withdraw CTA description" ) static let deposit = NSLocalizedString( "Add %@ to Rewards Account", comment: "Account Actions: Rewards deposit CTA description" ) } enum Exchange { static let withdraw = NSLocalizedString( "Withdraw %@ from Exchange", comment: "Account Actions: Exchange withdraw CTA description" ) static let deposit = NSLocalizedString( "Add %@ to Exchange", comment: "Account Actions: Exchange deposit CTA description" ) } static let buy = NSLocalizedString( "Use Your Cash or Card", comment: "Account Actions: Buy CTA description" ) static let sell = NSLocalizedString( "Convert Your Crypto to Cash", comment: "Account Actions: Sell CTA description" ) static let send = NSLocalizedString( "Transfer %@ to Other Wallets", comment: "Account Actions: Send CTA description" ) static let receive = NSLocalizedString( "Receive %@ to your account", comment: "Account Actions: Receive CTA description" ) static let swap = NSLocalizedString( "Exchange %@ for Another Crypto", comment: "Account Actions: Swap CTA description" ) static let activity = NSLocalizedString( "View all transactions", comment: "Account Actions: Activity CTA description" ) } } } }
lgpl-3.0
66c05c964d6ab4d7c9b7cfbc19674905
38.233645
85
0.452358
6.738363
false
false
false
false
miDrive/MDAlert
MDAlert/Classes/MDAlertViewDefaults.swift
1
1750
// // MDAlertViewDefaults.swift // Pods // // Created by Chris Byatt on 12/05/2017. // // import Foundation class MDAlertViewDefaults { // Default backgorund colour of alert static let alertBackgroundColour: UIColor = UIColor.white // Default height of actions static let alertButtonHeight: CGFloat = 60 // Default corner radius of alert static let alertCornerRadius: CGFloat = 5.0 // Default font for alert title static let titleFont: UIFont = UIFont.systemFont(ofSize: 26.0) // Default colour for alert title static let titleColour: UIColor = UIColor.black // Default font alert message static let bodyFont: UIFont = UIFont.systemFont(ofSize: 16.0) // Default colour for alert message static let bodyColour: UIColor = UIColor.black // Default background colour of action static let actionDefaultBackgroundColour: UIColor = UIColor(red: 4/255, green: 123/255, blue: 205/255, alpha: 1.0) // Default background colour of cancel action static let actionCancelBackgroundColour: UIColor = UIColor(red: 135/255, green: 154/255, blue: 168/255, alpha: 1.0) // Default background colour of destructive action static let actionDestructiveBackgroundColour: UIColor = UIColor(red: 235/255, green: 0/255, blue: 0/255, alpha: 1.0) // Default title colour of action static let actionDefaultTitleColour: UIColor = UIColor.white // Default title colour of destructive action static let actionDestructiveTitleColour: UIColor = UIColor.white // Default title colour of cancel action static let actionCancelTitleColour: UIColor = UIColor.white // Default action font static let actionTitleFont: UIFont = UIFont.systemFont(ofSize: 15.0) }
mit
400c843f7eeb4407a44b007019282262
31.407407
120
0.725143
4.441624
false
false
false
false
guillermo-ag-95/App-Development-with-Swift-for-Students
2 - Introduction to UIKit/1 - Strings/lab/Lab - Strings.playground/Pages/5. App Exercise - Password Entry and User Search.xcplaygroundpage/Contents.swift
1
3211
/*: ## App Exercise - Password Entry and User Search >These exercises reinforce Swift concepts in the context of a fitness tracking app. You think it might be fun to incorporate some friendly competition into your fitness tracking app. Users will be able to compete with friends in small fitness challenges. However, to do this users will need a password-protected account. Write an if-else statement below that will check that the entered user name and password match the stored user name and password. While the password should be case sensitive, users should be able to log in even if their entered user name has the wrong capitalization. If the user name and password match, print "You are now logged in!" Otherwise, print "Please check your user name and password and try again." */ let storedUserName = "TheFittest11" let storedPassword = "a8H1LuK91" let enteredUserName = "thefittest11" let enteredPassword: String = "a8H1Luk9" if storedUserName.lowercased() == enteredUserName.lowercased() && storedPassword == enteredPassword { print("You are now logged in!") } else { print("Please check your user name and password and try again.") } /*: Now that users can log in, they need to be able to search through a list of users to find their friends. This might normally be done by having the user enter a name, and then looping through all user names to see if a user name contains the search term entered. You'll learn about loops later, so for now you'll just work through one cycle of that. Imagine you are searching for a friend whose user name is StepChallenger. You enter "step" into a search bar and the app begins to search. When the app comes to the user name "stepchallenger," it checks to see if "StepChallenger" contains "step." Using `userName` and `searchName` below, write an if-else statement that checks to see if `userName` contains the search term. The search should *not* be case sensitive. */ import Foundation let userName = "StepChallenger" let searchName = "step" if userName.lowercased().contains(searchName) { print("There it is.") } /*: _Copyright © 2017 Apple Inc._ _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._ */ //: [Previous](@previous) | page 5 of 5
mit
d2ba084bdd157aa59448cd887785b91b
79.25
648
0.772586
4.508427
false
false
false
false
jovito-royeca/Cineko
Cineko/DynamicHeightTableViewCell.swift
1
1146
// // DynamicHeightTableViewCell.swift // Cineko // // Created by Jovit Royeca on 12/04/2016. // Copyright © 2016 Jovito Royeca. All rights reserved. // import UIKit class DynamicHeightTableViewCell: UITableViewCell { @IBOutlet weak var dynamicLabel: UILabel! // MARK: Overrides override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } // MARK: Custom Methods func changeColor(backgroundColor: UIColor?, fontColor: UIColor?) { self.backgroundColor = backgroundColor dynamicLabel.textColor = fontColor if accessoryType != .None { if let image = UIImage(named: "forward") { let tintedImage = image.imageWithRenderingMode(.AlwaysTemplate) let imageView = UIImageView(image: tintedImage) imageView.tintColor = fontColor accessoryView = imageView } } } }
apache-2.0
f3d59aa26312a41a8efc6a5dc6e50295
26.926829
79
0.627948
5.276498
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/SkipWhile.swift
6
3228
// // SkipWhile.swift // Rx // // Created by Yury Korolev on 10/9/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // class SkipWhileSink<ElementType, O: ObserverType> : Sink<O>, ObserverType where O.E == ElementType { typealias Parent = SkipWhile<ElementType> typealias Element = ElementType fileprivate let _parent: Parent fileprivate var _running = false init(parent: Parent, observer: O) { _parent = parent super.init(observer: observer) } func on(_ event: Event<Element>) { switch event { case .next(let value): if !_running { do { _running = try !_parent._predicate(value) } catch let e { forwardOn(.error(e)) dispose() return } } if _running { forwardOn(.next(value)) } case .error, .completed: forwardOn(event) dispose() } } } class SkipWhileSinkWithIndex<ElementType, O: ObserverType> : Sink<O>, ObserverType where O.E == ElementType { typealias Parent = SkipWhile<ElementType> typealias Element = ElementType fileprivate let _parent: Parent fileprivate var _index = 0 fileprivate var _running = false init(parent: Parent, observer: O) { _parent = parent super.init(observer: observer) } func on(_ event: Event<Element>) { switch event { case .next(let value): if !_running { do { _running = try !_parent._predicateWithIndex(value, _index) let _ = try incrementChecked(&_index) } catch let e { forwardOn(.error(e)) dispose() return } } if _running { forwardOn(.next(value)) } case .error, .completed: forwardOn(event) dispose() } } } class SkipWhile<Element>: Producer<Element> { typealias Predicate = (Element) throws -> Bool typealias PredicateWithIndex = (Element, Int) throws -> Bool fileprivate let _source: Observable<Element> fileprivate let _predicate: Predicate! fileprivate let _predicateWithIndex: PredicateWithIndex! init(source: Observable<Element>, predicate: @escaping Predicate) { _source = source _predicate = predicate _predicateWithIndex = nil } init(source: Observable<Element>, predicate: @escaping PredicateWithIndex) { _source = source _predicate = nil _predicateWithIndex = predicate } override func run<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { if let _ = _predicate { let sink = SkipWhileSink(parent: self, observer: observer) sink.disposable = _source.subscribe(sink) return sink } else { let sink = SkipWhileSinkWithIndex(parent: self, observer: observer) sink.disposable = _source.subscribe(sink) return sink } } }
mit
fd766842a2e3f357452a0483c699719d
27.06087
109
0.548807
4.852632
false
false
false
false
LuisMarinheiro/FastlaneExample
FastlaneExample/Models/Repository.swift
4
5122
// // Repository.swift // FastlaneExample // // Created by Ivan Bruel on 30/05/2017. // Copyright © 2017 Swift Aveiro. All rights reserved. // import Foundation import ObjectMapper struct Repository: ImmutableMappable { let keysURL: String let statusesURL: String let issuesURL: String let defaultBranch: String let issueEventsURL: String? let identifier: Int let owner: User let eventsURL: String let subscriptionURL: String let watchers: Int let gitCommitsURL: String let subscribersURL: String let cloneURL: String let hasWiki: Bool let URL: String let pullsURL: String let fork: Bool let notificationsURL: String let description: String? let collaboratorsURL: String let deploymentsURL: String let languagesURL: String let hasIssues: Bool let commentsURL: String let isPrivate: Bool let size: Int let gitTagsURL: String let updatedAt: String let sshURL: String let name: String let contentsURL: String let archiveURL: String let milestonesURL: String let blobsURL: String let contributorsURL: String let openIssuesCount: Int let forksCount: Int let treesURL: String let svnURL: String let commitsURL: String let createdAt: String let forksURL: String let hasDownloads: Bool let mirrorURL: String? let homepage: String? let teamsURL: String let branchesURL: String let issueCommentURL: String let mergesURL: String let gitRefsURL: String let gitURL: String let forks: Int let openIssues: Int let hooksURL: String let htmlURL: URL let stargazersURL: String let assigneesURL: String let compareURL: String let fullName: String let tagsURL: String let releasesURL: String let pushedAt: String? let labelsURL: String let downloadsURL: String let stargazersCount: Int let watchersCount: Int let language: String let hasPages: Bool var isSwift: Bool { return language == "Swift" } // swiftlint:disable next function_body_length init(map: Map) throws { keysURL = try map.value("keys_url") statusesURL = try map.value("statuses_url") issuesURL = try map.value("issues_url") defaultBranch = try map.value("default_branch") issueEventsURL = try? map.value("issues_events_url") identifier = try map.value("id") owner = try map.value("owner") eventsURL = try map.value("events_url") subscriptionURL = try map.value("subscription_url") watchers = try map.value("watchers") gitCommitsURL = try map.value("git_commits_url") subscribersURL = try map.value("subscribers_url") cloneURL = try map.value("clone_url") hasWiki = try map.value("has_wiki") URL = try map.value("url") pullsURL = try map.value("pulls_url") fork = try map.value("fork") notificationsURL = try map.value("notifications_url") description = try? map.value("description") collaboratorsURL = try map.value("collaborators_url") deploymentsURL = try map.value("deployments_url") languagesURL = try map.value("languages_url") hasIssues = try map.value("has_issues") commentsURL = try map.value("comments_url") isPrivate = try map.value("private") size = try map.value("size") gitTagsURL = try map.value("git_tags_url") updatedAt = try map.value("updated_at") sshURL = try map.value("ssh_url") name = try map.value("name") contentsURL = try map.value("contents_url") archiveURL = try map.value("archive_url") milestonesURL = try map.value("milestones_url") blobsURL = try map.value("blobs_url") contributorsURL = try map.value("contributors_url") openIssuesCount = try map.value("open_issues_count") forksCount = try map.value("forks_count") treesURL = try map.value("trees_url") svnURL = try map.value("svn_url") commitsURL = try map.value("commits_url") createdAt = try map.value("created_at") forksURL = try map.value("forks_url") hasDownloads = try map.value("has_downloads") mirrorURL = try? map.value("mirror_url") homepage = try? map.value("homepage") teamsURL = try map.value("teams_url") branchesURL = try map.value("branches_url") issueCommentURL = try map.value("issue_comment_url") mergesURL = try map.value("merges_url") gitRefsURL = try map.value("git_refs_url") gitURL = try map.value("git_url") forks = try map.value("forks") openIssues = try map.value("open_issues") hooksURL = try map.value("hooks_url") htmlURL = try map.value("html_url", using: URLTransform()) stargazersURL = try map.value("stargazers_url") assigneesURL = try map.value("assignees_url") compareURL = try map.value("compare_url") fullName = try map.value("full_name") tagsURL = try map.value("tags_url") releasesURL = try map.value("releases_url") pushedAt = try? map.value("pushed_at") labelsURL = try map.value("labels_url") downloadsURL = try map.value("downloads_url") stargazersCount = try map.value("stargazers_count") watchersCount = try map.value("watchers_count") language = try map.value("language") hasPages = try map.value("has_pages") } }
mit
08bc1b95bc9e28baeda47ddbc3dbcbb2
31.411392
62
0.696934
3.721657
false
false
false
false
jcheng77/missfit-ios
missfit/missfit/Vendor/Refresher/PullToRefreshExtension.swift
1
3129
// // PullToRefresh.swift // // Copyright (c) 2014 Josip Cavar // // 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 UIKit private let pullToRefreshTag = 324 private let pullToRefreshDefaultHeight: CGFloat = 50 extension UIScrollView { // Actual UIView subclass which is added as subview to desired UIScrollView. If you want customize appearance of this object, do that after addPullToRefreshWithAction public var pullToRefreshView: PullToRefreshView? { get { var pullToRefreshView = viewWithTag(pullToRefreshTag) return pullToRefreshView as? PullToRefreshView } } // If you want to add pull to refresh functionality to your UIScrollView just call this method and pass action closure you want to execute while pull to refresh is animating. If you want to stop pull to refresh you must do that manually calling stopPullToRefreshView methods on your scroll view public func addPullToRefreshWithAction(action :(() -> ())) { var pullToRefreshView = PullToRefreshView(action: action, frame: CGRectMake(0, -pullToRefreshDefaultHeight, self.frame.size.width, pullToRefreshDefaultHeight)) pullToRefreshView.tag = pullToRefreshTag addSubview(pullToRefreshView) } // If you want to use your custom animation when pull to refresh is animating, you should call this method and pass your animator object. public func addPullToRefreshWithAction(action :(() -> ()), withAnimator animator: PullToRefreshViewAnimator) { var pullToRefreshView = PullToRefreshView(action: action, frame: CGRectMake(0, -pullToRefreshDefaultHeight, self.frame.size.width, pullToRefreshDefaultHeight), animator: animator) pullToRefreshView.tag = pullToRefreshTag addSubview(pullToRefreshView) } // Manually start pull to refresh public func startPullToRefresh() { pullToRefreshView?.loading = true } // Manually stop pull to refresh public func stopPullToRefresh() { pullToRefreshView?.loading = false } }
mit
0f9a87cd4a490a35f6eebb69cd55b81d
45.029412
298
0.740812
5.330494
false
false
false
false
ciiqr/contakt
contakt/contaktTests/String+insensitiveContains-Tests.swift
1
2020
// // String+insensitiveContains-Tests.swift // contakt // // Created by William Villeneuve on 2016-01-24. // Copyright © 2016 William Villeneuve. All rights reserved. // import XCTest class String_insensitiveContains_Tests: XCTestCase { func test_string_lower_contains() { let string = "this is a string" XCTAssert(string.insensitiveContains("a STR")) XCTAssert(string.insensitiveContains("THIS")) XCTAssert(string.insensitiveContains("this is a string")) } func test_string_upper_contains() { let string = "THIS IS A STRING" XCTAssert(string.insensitiveContains("a STR")) XCTAssert(string.insensitiveContains("THIS")) XCTAssert(string.insensitiveContains("this is a string")) } func test_string_someUpper_contains() { let string = "This is A STRING" XCTAssert(string.insensitiveContains("a STR")) XCTAssert(string.insensitiveContains("THIS")) XCTAssert(string.insensitiveContains("this is a string")) } func test_characterView_lower_contains() { let string = "this is a string" XCTAssert(string.insensitiveContains("a STR".characters)) XCTAssert(string.insensitiveContains("THIS".characters)) XCTAssert(string.insensitiveContains("this is a string".characters)) } func test_characterView_upper_contains() { let string = "THIS IS A STRING" XCTAssert(string.insensitiveContains("a STR".characters)) XCTAssert(string.insensitiveContains("THIS".characters)) XCTAssert(string.insensitiveContains("this is a string".characters)) } func test_characterView_someUpper_contains() { let string = "This is A STRING" XCTAssert(string.insensitiveContains("a STR".characters)) XCTAssert(string.insensitiveContains("THIS".characters)) XCTAssert(string.insensitiveContains("this is a string".characters)) } }
unlicense
9573bd4762a0a1ca8cc327fa0f4e2250
32.65
76
0.660228
4.641379
false
true
false
false
hooman/swift
test/Interpreter/class_forbid_objc_assoc_objects.swift
5
8591
// RUN: %target-run-simple-swift // RUN: %target-run-simple-swift(-O) // REQUIRES: objc_interop // REQUIRES: executable_test import ObjectiveC import StdlibUnittest defer { runAllTests() } var Tests = TestSuite("AssocObject") @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) final class AllowedToHaveAssocObject { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("no crash when set assoc object, assign") { let x = AllowedToHaveAssocObject() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_ASSIGN) } Tests.test("no crash when set assoc object, copy") { let x = AllowedToHaveAssocObject() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_COPY) } Tests.test("no crash when set assoc object, copy_nonatomic") { let x = AllowedToHaveAssocObject() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_COPY_NONATOMIC) } Tests.test("no crash when set assoc object, retain") { let x = AllowedToHaveAssocObject() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } Tests.test("no crash when set assoc object, retain_nonatomic") { let x = AllowedToHaveAssocObject() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) @_semantics("objc.forbidAssociatedObjects") final class UnableToHaveAssocObjects { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("crash when set assoc object, assign") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnableToHaveAssocObjects() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_ASSIGN) } Tests.test("crash when set assoc object, copy") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnableToHaveAssocObjects() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_COPY) } Tests.test("crash when set assoc object, copy_nonatomic") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnableToHaveAssocObjects() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_COPY_NONATOMIC) } Tests.test("crash when set assoc object, retain") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnableToHaveAssocObjects() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } Tests.test("crash when set assoc object, retain_nonatomic") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnableToHaveAssocObjects() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) @_semantics("objc.forbidAssociatedObjects") final class UnableToHaveAssocObjectsGeneric<T> { var state: T init(state: T) { self.state = state } } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("crash when set assoc object (generic)") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnableToHaveAssocObjectsGeneric(state: 5) objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } } // In this case, we mark the child. This is unsound since we will get different // answers since the type checker isn't enforcing this. @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) class UnsoundAbleToHaveAssocObjectsParentClass { } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) @_semantics("objc.forbidAssociatedObjects") final class UnsoundUnableToHaveAssocObjectsSubClass : UnsoundAbleToHaveAssocObjectsParentClass { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("no crash when set assoc object set only on child subclass, but assoc to parent") .code { let x = UnsoundAbleToHaveAssocObjectsParentClass() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } Tests.test("crash when set assoc object set only on child subclass") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnsoundUnableToHaveAssocObjectsSubClass() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } } // In this case, we mark the parent. It seems like the bit is propagated... I am // not sure. @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) @_semantics("objc.forbidAssociatedObjects") class UnsoundAbleToHaveAssocObjectsParentClass2 { } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) final class UnsoundUnableToHaveAssocObjectsSubClass2 : UnsoundAbleToHaveAssocObjectsParentClass2 { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("crash when set assoc object set only on parent class") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnsoundUnableToHaveAssocObjectsSubClass2() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) class UnsoundUnableToHaveAssocObjectsSubClass3 : UnsoundAbleToHaveAssocObjectsParentClass2 { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("crash when set assoc object set only on parent class, child not final") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnsoundUnableToHaveAssocObjectsSubClass3() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } } // More Generic Tests // In this case, we mark the child. This is unsound since we will get different // answers since the type checker isn't enforcing this. @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) class GenericAbleToHaveAssocObjectsParentClass<T> { public var state: T init(state: T) { self.state = state } } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) @_semantics("objc.forbidAssociatedObjects") final class GenericUnableToHaveAssocObjectsSubClass<T> : GenericAbleToHaveAssocObjectsParentClass<T> { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("no crash when set assoc object set only on child subclass, but assoc to parent") .code { let x = GenericAbleToHaveAssocObjectsParentClass(state: 5) objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } Tests.test("crash when set assoc object set only on child subclass") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = GenericUnableToHaveAssocObjectsSubClass(state: 5) objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } } // In this case, we mark the parent. It seems like the bit is propagated... I am // not sure. @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) @_semantics("objc.forbidAssociatedObjects") class GenericAbleToHaveAssocObjectsParentClass2<T> { public var state: T init(state: T) { self.state = state } } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) final class GenericUnableToHaveAssocObjectsSubClass2<T> : GenericAbleToHaveAssocObjectsParentClass2<T> { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("crash when set assoc object set only on parent class") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = GenericUnableToHaveAssocObjectsSubClass2(state: 5) objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) class GenericUnableToHaveAssocObjectsSubClass3<T> : GenericAbleToHaveAssocObjectsParentClass2<T> { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("crash when set assoc object set only on parent class, child not final") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = GenericUnableToHaveAssocObjectsSubClass3(state: 5) objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } }
apache-2.0
798e90218493509b376efef6cfdce975
34.945607
104
0.728204
3.578092
false
true
false
false
Keanyuan/SwiftContact
SwiftContent/SwiftContent/Classes/PhotoBrower/LLPhotoBrowser/LLBrowserActionSheet.swift
1
8110
// // LLBrowserActionSheet.swift // LLPhotoBrowser // // Created by LvJianfeng on 2017/4/18. // Copyright © 2017年 LvJianfeng. All rights reserved. // import UIKit typealias LLDidSelectedCell = (NSInteger) -> Void open class LLBrowserActionSheet: UIView, UITableViewDelegate, UITableViewDataSource { /// Title Array fileprivate var titleArray: [String]? /// Cancel Title fileprivate var cancelTitle: String = "取消" /// Did Selected fileprivate var didSelectedAction: LLDidSelectedCell? = nil /// TableView fileprivate var tableView: UITableView? /// Mask View fileprivate var backMaskView: UIView? /// Height fileprivate var tableViewHeight: CGFloat? /// Cell Height fileprivate var tableCellHeight: CGFloat? /// Section View Background Color default: 191.0 191.0 191.0 fileprivate var sectionViewBackgroundColor: UIColor? = UIColor.init(red: 191.0/255.0, green: 191.0/255.0, blue: 191.0/255.0, alpha: 1.0) /// Cell Background Color fileprivate var cellBackgroundColor: UIColor? = UIColor.white /// Title Font fileprivate var titleFont: UIFont? = UIFont.systemFont(ofSize: 14.0) /// Title Color fileprivate var titleTextColor: UIColor? = UIColor.black /// Cancel Color fileprivate var cancelTextColor: UIColor? = UIColor.black /// Line Color fileprivate var lineColor: UIColor? = UIColor.init(red: 212.0/255.0, green: 212.0/255.0, blue: 212.0/255.0, alpha: 1.0) /// Init init(titleArray: [String] = [], cancelTitle: String, cellHeight: CGFloat? = 44.0, backgroundColor: UIColor?, cellBackgroundColor: UIColor, titleFont: UIFont?, titleTextColor: UIColor?, cancelTextColor: UIColor?, lineColor: UIColor?, didSelectedCell:LLDidSelectedCell? = nil) { super.init(frame: CGRect.zero) self.titleArray = titleArray self.cancelTitle = cancelTitle self.tableCellHeight = cellHeight if let _ = backgroundColor { self.sectionViewBackgroundColor = backgroundColor } if let _ = titleFont { self.titleFont = titleFont } if let _ = titleTextColor { self.titleTextColor = titleTextColor } if let _ = cancelTextColor { self.cancelTextColor = cancelTextColor } if let _ = lineColor { self.lineColor = lineColor } self.cellBackgroundColor = cellBackgroundColor self.tableViewHeight = CGFloat((self.titleArray?.count)! + 1) * self.tableCellHeight! + 10.0 self.didSelectedAction = didSelectedCell setupActionSheet() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupActionSheet() { backMaskView = UIView.init() backMaskView?.backgroundColor = UIColor.black backMaskView?.alpha = 0 // 渐变效果 UIView.animate(withDuration: 0.3) { self.backMaskView?.alpha = 0.3 } addSubview(backMaskView!) tableView = UITableView.init() tableView?.delegate = self tableView?.dataSource = self tableView?.separatorColor = UIColor.clear tableView?.bounces = false addSubview(tableView!) } // MARK: UITableViewDataSource public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return (section == 1) ? 10.0 : 0 } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 1 { let view = UIView.init() view.backgroundColor = sectionViewBackgroundColor! return view } return nil } public func numberOfSections(in tableView: UITableView) -> Int { return 2 } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return tableCellHeight! } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (section == 0) ? (titleArray?.count)! : 1 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier: String = "LLBrowserActionSheetCell" var cell: LLBrowserActionSheetCell? = tableView.dequeueReusableCell(withIdentifier: identifier) as? LLBrowserActionSheetCell if cell == nil { cell = LLBrowserActionSheetCell.init(style: .default, reuseIdentifier: identifier) } cell?.backgroundColor = cellBackgroundColor! cell?.titleLabel?.frame = CGRect.init(x: 0, y: 0, width: ll_w, height: tableCellHeight!) cell?.titleLabel?.font = titleFont! cell?.titleLabel?.textColor = titleTextColor! cell?.bottomLine?.backgroundColor = lineColor! cell?.bottomLine?.isHidden = true if indexPath.section == 0 { cell?.titleLabel?.text = titleArray?[indexPath.row] if (titleArray?.count)! > indexPath.row + 1 { cell?.bottomLine?.frame = CGRect.init(x: 0, y: tableCellHeight! - (1.0 / UIScreen.main.scale), width: self.ll_w, height: 1.0 / UIScreen.main.scale) cell?.bottomLine?.isHidden = false } }else{ cell?.titleLabel?.textColor = cancelTextColor! cell?.titleLabel?.text = cancelTitle } return cell! } // MARK: UITableViewDelegate public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 0{ if let didSelected = didSelectedAction { didSelected(indexPath.row) } } dismiss() } override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { dismiss() } func show(_ view: UIView) { view.addSubview(self) self.backgroundColor = UIColor.clear self.frame = view.bounds backMaskView?.frame = view.bounds tableView?.frame = CGRect.init(x: 0, y: ll_h, width: ll_w, height: tableViewHeight!) UIView.animate(withDuration: 0.3) { var frame = self.tableView?.frame frame?.origin.y -= self.tableViewHeight! self.tableView?.frame = frame! } } func dismiss() { UIView.animate(withDuration: 0.2, animations: { var frame = self.tableView?.frame frame?.origin.y += self.tableViewHeight! self.tableView?.frame = frame! self.backMaskView?.alpha = 0 }) { (finished) in self.removeFromSuperview() } } func updateFrameByTransform() { // Update if let _ = self.superview { self.frame = (self.superview?.bounds)! backMaskView?.frame = (self.superview?.bounds)! tableView?.frame = CGRect.init(x: 0, y: ll_h - tableViewHeight!, width: ll_w, height: tableViewHeight!) tableView?.reloadData() } } } class LLBrowserActionSheetCell: UITableViewCell { public var titleLabel: UILabel? public var bottomLine: UIView? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) createCell() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func createCell() { titleLabel = UILabel.init() titleLabel?.textAlignment = .center contentView.addSubview(titleLabel!) bottomLine = UILabel.init() bottomLine?.backgroundColor = UIColor.init(red: 212.0/255.0, green: 212.0/255.0, blue: 212.0/255.0, alpha: 1.0) contentView.addSubview(bottomLine!) } }
mit
619cb92b37b4376d95d857736c4191c5
33.012605
280
0.6147
4.879445
false
false
false
false
aldopolimi/mobilecodegenerator
examples/ParkTraining/generated/ios/ParkTraining/ParkTraining/PhotoNewViewController.swift
2
3044
import UIKit import MobileCoreServices class PhotoNewViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet weak var savePhotoButton: UIButton! @IBOutlet weak var takenPhoto: UIImageView! override func viewDidLoad() { super.viewDidLoad() savePhotoButton.layer.cornerRadius = 2 } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) } @IBAction func savePhotoButtonTouchDown(sender: UIButton) { //TODO Implement the action } @IBAction func savePhotoButtonTouchUpInside(sender: UIButton) { //TODO Implement the action } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let mediaType = info[UIImagePickerControllerMediaType] as! NSString if mediaType.isEqualToString(kUTTypeImage as String) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage self.takenPhoto.image = image UIImageWriteToSavedPhotosAlbum(image, self, #selector(PhotoNewViewController.completionSelector(wasSavedSuccessfully:didFinishSavingWithError:contextInfo:)), nil) } dismissViewControllerAnimated(true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func completionSelector(wasSavedSuccessfully saved: Bool, didFinishSavingWithError error: NSErrorPointer, contextInfo:UnsafePointer<Void>) { if error != nil { let alert = UIAlertController(title: "Save Failed", message: "Failed to save from camera", preferredStyle: UIAlertControllerStyle.Alert) let cancelAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } // Check your model // You are missing the videocameraController or it does not match the videoview id } @IBAction func openPhotoCamera(sender: UIButton) { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) { let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .Camera picker.mediaTypes = [kUTTypeImage as String] presentViewController(picker, animated: true, completion: nil) } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { } }
gpl-3.0
03099bf1bbf4a6f16b181c10ba425c59
27.448598
171
0.722733
5.221269
false
false
false
false
danielpi/Swift-Playgrounds
Swift-Playgrounds/Swift Stanard Library/String.playground/section-1.swift
1
1927
// Swift Standard Library - Types - String // A String represents an ordered collection of characters. // Creating a String let emptyString = String() let equivilentString = "" let repeatedString = String(count: 5, repeatedValue: Character("a")) // Querying a String var string = "Hello, world!" let firstCheck = string.isEmpty string = "" let secondCheck = string.isEmpty string = "Hello, world!" let hasPrefixFirstCheck = string.hasPrefix("Hello") let hasPrefixSecondCheck = string.hasPrefix("hello") let hasSuffixFirstCheck = string.hasSuffix("world!") let hasSuffixSecondCheck = string.hasSuffix("World!") // Changing and Converting Strings string = "42" if let number = Int(string) { print("Got the number: \(number)") } else { print("Couldn't convert to a number") } // Operators // Concatinate + let combination = "Hello " + "world" // You can use the + operator with two strings as shown in the combination example, or with a string and a character in either order: let exclamationPoint: Character = "!" var charCombo = combination charCombo.append(exclamationPoint) //var extremeCombo: String = exclamationPoint //extremeCombo.append(charCombo) // Append += string = "Hello " string += "world" string.append(exclamationPoint) string // Equality == let string1 = "Hello world!" let string2 = "Hello" + " " + "world" + "!" let equality = string1 == string2 // Less than < let stringGreater = "Number 3" let stringLesser = "Number 2" let resulNotLessThan = stringGreater < stringLesser let resultIsLessThan = stringLesser < stringGreater // What is missing from this chapter? // - How does the less than operator work? "abc" < "def" "def" < "abc" "Number 2" < "number 1" // It just looks at the ordinal valu of the first character??? // - Does the greater than symbol work? "abc" > "def" "def" > "abc" "Number 2" > "number 1" // - How do you access the rodinal values of Characters?
mit
b3a601196f40fa3a4deef8137487edd0
21.149425
133
0.71095
3.663498
false
false
false
false
liuchuo/Swift-practice
20150619-6/20150619-6/MasterViewController.swift
1
3658
// // MasterViewController.swift // 20150619-6 // // Created by 欣 陈 on 15/6/19. // Copyright (c) 2015年 欣 陈. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [AnyObject]() override func awakeFromNib() { super.awakeFromNib() if UIDevice.currentDevice().userInterfaceIdiom == .Pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } } 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: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController } } 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) as! UITableViewCell 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. } } }
gpl-2.0
4daa8fd3bb794b705201ac565e791728
36.608247
157
0.683936
5.620955
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Settings/ViewControllers/BrowserConfigurationViewController.swift
1
2704
// Copyright DApps Platform Inc. All rights reserved. import Foundation import UIKit import Eureka import WebKit import Realm protocol BrowserConfigurationViewControllerDelegate: class { func didPressDeleteCache(in controller: BrowserConfigurationViewController) } final class BrowserConfigurationViewController: FormViewController { let viewModel = BrowserConfigurationViewModel() let preferences: PreferencesController weak var delegate: BrowserConfigurationViewControllerDelegate? init( preferences: PreferencesController = PreferencesController() ) { self.preferences = preferences super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = viewModel.title form +++ Section() <<< PushRow<SearchEngine> { [weak self] in guard let `self` = self else { return } $0.title = self.viewModel.searchEngineTitle $0.options = self.viewModel.searchEngines $0.value = SearchEngine(rawValue: self.preferences.get(for: .browserSearchEngine)) ?? .default $0.selectorTitle = self.viewModel.searchEngineTitle $0.displayValueFor = { $0?.title } }.onChange { [weak self] row in guard let value = row.value else { return } self?.preferences.set(value: value.rawValue, for: .browserSearchEngine) }.onPresent { _, selectorController in selectorController.sectionKeyForValue = { _ in return "" } } +++ Section() <<< AppFormAppearance.button { [weak self] in guard let `self` = self else { return } $0.title = self.viewModel.clearBrowserCacheTitle }.onCellSelection { [weak self] _, _ in self?.confirmClear() }.cellUpdate { cell, _ in cell.textLabel?.textAlignment = .left cell.textLabel?.textColor = .black } } private func confirmClear() { confirm( title: viewModel.clearBrowserCacheConfirmTitle, message: viewModel.clearBrowserCacheConfirmMessage, okTitle: R.string.localizable.delete(), okStyle: .destructive, completion: { [weak self] result in guard let `self` = self else { return } switch result { case .success: self.delegate?.didPressDeleteCache(in: self) case .failure: break } } ) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-3.0
377d4d06bd674ee89ffeabc075aa5cd2
31.97561
106
0.611686
5.150476
false
true
false
false
ChaselAn/ACTagView
ACTagViewDemo/ACTagView/ACTagButton.swift
1
1686
// // ACTagButton.swift // ACTagViewDemo // // Created by ac on 2017/7/30. // Copyright © 2017年 ac. All rights reserved. // import UIKit open class ACTagButton: UIButton { open var tagAttribute = ACTagAttribute() { didSet { setUpUI() } } override public init(frame: CGRect) { super.init(frame: frame) isUserInteractionEnabled = false isSelected = false } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open var isSelected: Bool { didSet { if isSelected { backgroundColor = tagAttribute.selectedBackgroundColor layer.borderColor = tagAttribute.selectedBorderColor.cgColor } else { backgroundColor = tagAttribute.backgroundColor layer.borderColor = tagAttribute.borderColor.cgColor } } } private func setUpUI() { setTitle(tagAttribute.text, for: .normal) setTitleColor(tagAttribute.textColor, for: .normal) setTitleColor(tagAttribute.selectedTextColor, for: .selected) backgroundColor = tagAttribute.backgroundColor layer.borderWidth = tagAttribute.borderWidth titleLabel?.font = tagAttribute.font setBorderTyper(tagAttribute.borderType) } private func setBorderTyper(_ type: ACTagBorderType) { superview?.layoutIfNeeded() switch type { case .halfOfCircle: layer.cornerRadius = frame.height / 2 layer.masksToBounds = true case .custom(radius: let radius): layer.cornerRadius = radius layer.masksToBounds = true case .none: layer.cornerRadius = 0 layer.masksToBounds = false } } }
mit
8064eaf9d09d877b1a5953427c03e1c3
23.391304
68
0.675579
4.585831
false
false
false
false
venticake/RetricaImglyKit-iOS
RetricaImglyKit/Classes/Frontend/Stores/ImageStore.swift
1
3807
// This file is part of the PhotoEditor Software Development Kit. // Copyright (C) 2016 9elements GmbH <[email protected]> // All rights reserved. // Redistribution and use in source and binary forms, without // modification, are permitted provided that the following license agreement // is approved and a legal/financial contract was signed by the user. // The license agreement can be found under the following link: // https://www.photoeditorsdk.com/LICENSE.txt import UIKit /** The `JSONStore` provides methods to retrieve JSON data from any URL. */ @available(iOS 8, *) @objc(IMGLYImageStoreProtocol) public protocol ImageStoreProtocol { /** Retrieves JSON data from the specified URL. - parameter url: A valid URL. - parameter completionBlock: A completion block. */ func get(url: NSURL, completionBlock: (UIImage?, NSError?) -> Void) } /** The `JSONStore` class provides methods to retrieve JSON data from any URL. It also caches the data due to efficiency. */ @available(iOS 8, *) @objc(IMGLYImageStore) public class ImageStore: NSObject, ImageStoreProtocol { /// A shared instance for convenience. public static let sharedStore = ImageStore() /// A service that is used to perform http get requests. public var requestService: RequestServiceProtocol = RequestService() private var store = NSCache() /// Whether or not to display an activity indicator while fetching the images. Default is `true`. public var showSpinner = true /** Retrieves JSON data from the specified URL. - parameter url: A valid URL. - parameter completionBlock: A completion block. */ public func get(url: NSURL, completionBlock: (UIImage?, NSError?) -> Void) { if let image = store[url] as? UIImage { completionBlock(image, nil) } else { if url.fileURL { if let data = NSData(contentsOfURL: url), image = UIImage(data: data) { if url.absoluteString.containsString(".9.") { completionBlock(image.resizableImageFrom9Patch(image), nil) } else { completionBlock(image, nil) } } else { let error = NSError(info: Localize("Image not found: ") + url.absoluteString) completionBlock(nil, error) } } else { startRequest(url, completionBlock: completionBlock) } } } private func startRequest(url: NSURL, completionBlock: (UIImage?, NSError?) -> Void) { showProgress() requestService.get(url, cached: true) { (data, error) -> Void in self.hideProgress() if error != nil { completionBlock(nil, error) } else { if let data = data { if var image = UIImage(data: data) { if url.absoluteString.containsString(".9.") { image = image.resizableImageFrom9Patch(image) } self.store[url] = image completionBlock(image, nil) } else { completionBlock(nil, NSError(info: "No image found at \(url).")) } } } } } private func showProgress() { if showSpinner { dispatch_async(dispatch_get_main_queue()) { ProgressView.sharedView.showWithMessage(Localize("Downloading...")) } } } private func hideProgress() { dispatch_async(dispatch_get_main_queue()) { ProgressView.sharedView.hide() } } }
mit
fc900b6164543b8a80008bb5d5c1f277
34.915094
101
0.579459
4.944156
false
false
false
false
kumabook/FeedlyKit
Source/Subscription.swift
1
4344
// // Subscription.swift // MusicFav // // Created by Hiroki Kumamoto on 12/21/14. // Copyright (c) 2014 Hiroki Kumamoto. All rights reserved. // import Foundation import SwiftyJSON public final class Subscription: Stream, ResponseObjectSerializable, ResponseCollectionSerializable, ParameterEncodable { public let id: String public let title: String public let categories: [Category] public let website: String? public let sortId: String? public let updated: Int64? public let added: Int64? public let visualUrl: String? public let iconUrl: String? public let coverUrl: String? public let subscribers: Int? public let velocity: Float? public let partial: Bool? public let coverColor: String? public let contentType: String? public let topic: [String]? public override var streamId: String { return id } public override var streamTitle: String { return title } public class func collection(_ response: HTTPURLResponse, representation: Any) -> [Subscription]? { let json = JSON(representation) return json.arrayValue.map({ Subscription(json: $0) }) } @objc required public convenience init?(response: HTTPURLResponse, representation: Any) { let json = JSON(representation) self.init(json: json) } public init(json: JSON) { self.id = json["id"].stringValue self.title = json["title"].stringValue self.website = json["website"].stringValue self.categories = json["categories"].arrayValue.map({Category(json: $0)}) self.sortId = json["sortid"].string self.updated = json["updated"].int64 self.added = json["added"].int64 self.visualUrl = json["visualUrl"].string self.iconUrl = json["iconUrl"].string self.coverUrl = json["coverUrl"].string self.subscribers = json["subscribers"].int self.velocity = json["velocity"].float self.partial = json["partial"].bool self.coverColor = json["coverColor"].string self.contentType = json["contentType"].string self.topic = json["topic"].arrayValue.map({ $0.stringValue }) } public init(feed: Feed, categories: [Category]) { self.id = feed.id self.title = feed.title self.website = nil self.categories = categories self.sortId = nil self.updated = nil self.added = nil self.visualUrl = feed.visualUrl self.iconUrl = feed.iconUrl self.coverUrl = feed.coverUrl self.subscribers = feed.subscribers self.velocity = feed.velocity self.partial = feed.partial self.coverColor = feed.coverColor self.contentType = feed.contentType self.topic = feed.topics } public convenience init(id: String, title: String, categories: [Category]) { self.init(id: id, title: title, visualUrl: nil, categories: categories) } public init(id: String, title: String, visualUrl: String?, categories: [Category]) { self.id = id self.title = title self.website = nil self.categories = categories self.sortId = nil self.updated = nil self.added = nil self.visualUrl = visualUrl self.iconUrl = nil self.coverUrl = nil self.subscribers = nil self.velocity = nil self.partial = nil self.coverColor = nil self.contentType = nil self.topic = nil } public func toParameters() -> [String : Any] { return [ "title": title, "id": id, "categories": categories.map({ $0.toParameters() }) ] } public override var thumbnailURL: URL? { if let url = visualUrl { return URL(string: url) } else if let url = coverUrl { return URL(string: url) } else if let url = iconUrl { return URL(string: url) } else { return nil } } }
mit
44dd7915c6989f3791f8116b5e65094a
31.177778
103
0.572053
4.482972
false
false
false
false
soapyigu/LeetCode_Swift
Array/MinimumSizeSubarraySum.swift
1
860
/** * Question Link: https://leetcode.com/problems/minimum-size-subarray-sum/ * Primary idea: Two Pointers, anchor the former and move forward the latter one to ensure the sum of subarray just covers the target * Note: There could be no invalid subarray which sum >= target * Time Complexity: O(n), Space Complexity: O(1) * */ class MinimumSizeSubarraySum { func minSubArrayLen(_ s: Int, _ nums: [Int]) -> Int { var miniSize = Int.max, start = 0, currentSum = 0 for (i, num) in nums.enumerated() { currentSum += num while currentSum >= s && start <= i { miniSize = min(miniSize, i - start + 1) currentSum -= nums[start] start += 1 } } return miniSize == Int.max ? 0 : miniSize } }
mit
cfb732a4e4bc35bcd3d13111aae850ca
32.115385
133
0.552326
4.174757
false
false
false
false
WSDOT/wsdot-ios-app
wsdot/AmtrakCascadesStore.swift
1
13610
// // AmtrakCascadesStore.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // 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 Alamofire import SwiftyJSON class AmtrakCascadesStore { typealias FetchAmtrakSchedulesCompletion = (_ data: [[(AmtrakCascadesServiceStopItem,AmtrakCascadesServiceStopItem?)]]?, _ error: Error?) -> () static func getSchedule(_ date: Date, originId: String, destId: String, completion: @escaping FetchAmtrakSchedulesCompletion) { let URL = "https://www.wsdot.wa.gov/traffic/api/amtrak/Schedulerest.svc/GetScheduleAsJson?AccessCode=" + ApiKeys.getWSDOTKey() + "&StatusDate=" + TimeUtils.formatTime(date, format: "MM/dd/yyyy") + "&TrainNumber=-1&FromLocation=" + originId + "&ToLocation=" + destId AF.request(URL).validate().responseJSON { response in switch response.result { case .success: if let value = response.data { let json = JSON(value) let serviceArrays = parseServiceItemsJSON(json) let servicePairs = getServiceStopPairs(serviceArrays) completion(servicePairs, nil) } case .failure(let error): print(error) completion(nil, error) } } } fileprivate static func parseServiceItemsJSON(_ json: JSON) -> [[AmtrakCascadesServiceStopItem]] { var tripItems = [[AmtrakCascadesServiceStopItem]]() var currentTripNum = -1 // current trip number - not the same as trip index b/c trips don't have to start at 0 or 1 var currentTripIndex = -1 // index into tripItems for (_, stationJson):(String, JSON) in json { if (currentTripNum != stationJson["TripNumber"].intValue) { tripItems.append([AmtrakCascadesServiceStopItem]()) currentTripNum = stationJson["TripNumber"].intValue currentTripIndex = currentTripIndex + 1 } let service = AmtrakCascadesServiceStopItem() service.stationId = stationJson["StationName"].stringValue service.stationName = stationJson["StationFullName"].stringValue service.trainNumber = stationJson["TrainNumber"].intValue service.tripNumer = stationJson["TripNumber"].intValue service.sortOrder = stationJson["SortOrder"].intValue service.arrivalComment = stationJson["ArrivalComment"].string service.departureComment = stationJson["DepartureComment"].string if let scheduledDepartureTime = stationJson["ScheduledDepartureTime"].string { service.scheduledDepartureTime = TimeUtils.parseJSONDateToNSDate(scheduledDepartureTime) } if let scheduledArrivalTime = stationJson["ScheduledArrivalTime"].string { service.scheduledArrivalTime = TimeUtils.parseJSONDateToNSDate(scheduledArrivalTime) } if service.scheduledDepartureTime == nil { service.scheduledDepartureTime = service.scheduledArrivalTime } if service.scheduledArrivalTime == nil { service.scheduledArrivalTime = service.scheduledDepartureTime } if let arrivComments = stationJson["ArrivalComment"].string { if (arrivComments.lowercased().contains("late")){ let mins = TimeUtils.getMinsFromString(arrivComments) service.arrivalComment = "Estimated " + arrivComments.lowercased() + " at " + TimeUtils.getTimeOfDay(service.scheduledArrivalTime!.addingTimeInterval(mins * 60)) } else if (arrivComments.lowercased().contains("early")){ let mins = TimeUtils.getMinsFromString(arrivComments) service.arrivalComment = "Estimated " + arrivComments.lowercased() + " at " + TimeUtils.getTimeOfDay(service.scheduledArrivalTime!.addingTimeInterval(mins * -60)) } else { service.arrivalComment = "Estimated " + arrivComments.lowercased() } } else { service.arrivalComment = "" } if let departComments = stationJson["ArrivalComment"].string { if (departComments.lowercased().contains("late")){ let mins = TimeUtils.getMinsFromString(departComments) service.departureComment = "Estimated " + departComments.lowercased() + " at " + TimeUtils.getTimeOfDay(service.scheduledDepartureTime!.addingTimeInterval(mins * 60)) } else if (departComments.lowercased().contains("early")){ let mins = TimeUtils.getMinsFromString(departComments) service.departureComment = "Estimated " + departComments.lowercased() + " at " + TimeUtils.getTimeOfDay(service.scheduledDepartureTime!.addingTimeInterval(mins * -60)) } else { service.departureComment = "Estimated " + departComments.lowercased() } } else { service.departureComment = "" } service.updated = TimeUtils.parseJSONDateToNSDate(stationJson["UpdateTime"].stringValue) tripItems[currentTripIndex].append(service) } return tripItems } // Creates origin-destination pairs from parsed JSON items of type [[AmtrakCascadesServiceStopItem]] // !!! Special case to consider is when the destination is not selected. In this case the pairs will have the destination value nil. static func getServiceStopPairs(_ servicesArrays: [[AmtrakCascadesServiceStopItem]]) -> [[(AmtrakCascadesServiceStopItem,AmtrakCascadesServiceStopItem?)]]{ var servicePairs = [[(AmtrakCascadesServiceStopItem,AmtrakCascadesServiceStopItem?)]]() var pairIndex = 0 for services in servicesArrays { servicePairs.append([(AmtrakCascadesServiceStopItem,AmtrakCascadesServiceStopItem?)]()) var serviceIndex = 0 // index in services loop for service in services { if (services.endIndex - 1 <= serviceIndex) && (services.count == 1) { // last item and there was only one service, add a nil servicePairs[pairIndex].append((service, nil)) } else if (serviceIndex + 1 <= services.endIndex - 1){ // Middle Item if service.stationId != services[serviceIndex + 1].stationId { // Stations will be listed twice when there is a transfer, don't add them twice servicePairs[pairIndex].append((service, services[serviceIndex + 1])) } } serviceIndex = serviceIndex + 1 } pairIndex = pairIndex + 1 } return servicePairs } // Builds an array of Station data for using in calculating the users distance from the station. static func getStations() -> [AmtrakCascadesStationItem]{ var stations = [AmtrakCascadesStationItem]() stations.append(AmtrakCascadesStationItem(id: "VAC", name: "Vancouver, BC", lat: 49.2737293, lon: -123.0979175)) stations.append(AmtrakCascadesStationItem(id: "BEL", name: "Bellingham, WA", lat: 48.720423, lon: -122.5109386)) stations.append(AmtrakCascadesStationItem(id: "MVW", name: "Mount Vernon, WA", lat: 48.4185923, lon: -122.334973)) stations.append(AmtrakCascadesStationItem(id: "STW", name: "Stanwood, WA", lat: 48.2417732, lon: -122.3495322)) stations.append(AmtrakCascadesStationItem(id: "EVR", name: "Everett, WA", lat: 47.975512, lon: -122.197854)) stations.append(AmtrakCascadesStationItem(id: "EDM", name: "Edmonds, WA", lat: 47.8111305, lon: -122.3841639)) stations.append(AmtrakCascadesStationItem(id: "SEA", name: "Seattle, WA", lat: 47.6001899, lon: -122.3314322)) stations.append(AmtrakCascadesStationItem(id: "TUK", name: "Tukwila, WA", lat: 47.461079, lon: -122.242693)) stations.append(AmtrakCascadesStationItem(id: "TAC", name: "Tacoma, WA", lat: 47.2419939, lon: -122.4205623)) stations.append(AmtrakCascadesStationItem(id: "OLW", name: "Olympia/Lacey, WA", lat: 46.9913576, lon: -122.793982)) stations.append(AmtrakCascadesStationItem(id: "CTL", name: "Centralia, WA", lat: 46.7177596, lon: -122.9528291)) stations.append(AmtrakCascadesStationItem(id: "KEL", name: "Kelso/Longview, WA", lat: 46.1422504, lon: -122.9132438)) stations.append(AmtrakCascadesStationItem(id: "VAN", name: "Vancouver, WA", lat: 45.6294472, lon: -122.685568)) stations.append(AmtrakCascadesStationItem(id: "PDX", name: "Portland, OR", lat: 45.528639, lon: -122.676284)) stations.append(AmtrakCascadesStationItem(id: "ORC", name: "Oregon City, OR", lat: 45.3659422, lon: -122.5960671)) stations.append(AmtrakCascadesStationItem(id: "SLM", name: "Salem, OR", lat: 44.9323665, lon: -123.0281591)) stations.append(AmtrakCascadesStationItem(id: "ALY", name: "Albany, OR", lat: 44.6300975, lon: -123.1041787)) stations.append(AmtrakCascadesStationItem(id: "EUG", name: "Eugene, OR", lat: 44.055506, lon: -123.094523)) return stations.sorted(by: {$0.name > $1.name}) } // Used to populate the destination selection static func getDestinationData() -> [String] { var dest = [String]() dest.append("Vancouver, BC") dest.append("Bellingham, WA") dest.append("Mount Vernon, WA") dest.append("Stanwood, WA") dest.append("Everett, WA") dest.append("Edmonds, WA") dest.append("Seattle, WA") dest.append("Tukwila, WA") dest.append("Tacoma, WA") dest.append("Olympia/Lacey, WA") dest.append("Centralia, WA") dest.append("Kelso/Longview, WA") dest.append("Vancouver, WA") dest.append("Portland, OR") dest.append("Oregon City, OR") dest.append("Salem, OR") dest.append("Albany, OR") dest.append("Eugene, OR") dest.sort() // dest.insert("All", at: 0) return dest } // Used to populate the origin selection static func getOriginData() -> [String]{ var origins = [String]() origins.append("Vancouver, BC") origins.append("Bellingham, WA") origins.append("Mount Vernon, WA") origins.append("Stanwood, WA") origins.append("Everett, WA") origins.append("Edmonds, WA") origins.append("Seattle, WA") origins.append("Tukwila, WA") origins.append("Tacoma, WA") origins.append("Olympia/Lacey, WA") origins.append("Centralia, WA") origins.append("Kelso/Longview, WA") origins.append("Vancouver, WA") origins.append("Portland, OR") origins.append("Oregon City, OR") origins.append("Salem, OR") origins.append("Albany, OR") origins.append("Eugene, OR") return origins.sorted() } // Station names to ID mapping. static let stationIdsMap: Dictionary<String, String> = [ "All": "N/A", "Vancouver, BC": "VAC", "Bellingham, WA": "BEL", "Mount Vernon, WA": "MVW", "Stanwood, WA": "STW", "Everett, WA": "EVR", "Edmonds, WA": "EDM", "Seattle, WA": "SEA", "Tukwila, WA": "TUK", "Tacoma, WA": "TAC", "Olympia/Lacey, WA": "OLW", "Centralia, WA": "CTL", "Kelso/Longview, WA": "KEL", "Vancouver, WA": "VAN", "Portland, OR": "PDX", "Oregon City, OR": "ORC", "Salem, OR": "SLM", "Albany, OR": "ALY", "Eugene, OR": "EUG" ] static let trainNumberMap: Dictionary<Int, String> = [ 7: "Empire Builder Train", 8: "Empire Builder Train", 11: "Coast Starlight Train", 14: "Coast Starlight Train", 27: "Empire Builder Train", 28: "Empire Builder Train", 500: "Amtrak Cascades Train", 501: "Amtrak Cascades Train", 502: "Amtrak Cascades Train", 503: "Amtrak Cascades Train", 504: "Amtrak Cascades Train", 505: "Amtrak Cascades Train", 506: "Amtrak Cascades Train", 507: "Amtrak Cascades Train", 508: "Amtrak Cascades Train", 509: "Amtrak Cascades Train", 510: "Amtrak Cascades Train", 511: "Amtrak Cascades Train", 512: "Amtrak Cascades Train", 513: "Amtrak Cascades Train", 516: "Amtrak Cascades Train", 517: "Amtrak Cascades Train", 518: "Amtrak Cascades Train", 519: "Amtrak Cascades Train" ] }
gpl-3.0
4999c8f60e84e08f13583ea59f006d2f
46.421603
187
0.615209
4.000588
false
false
false
false
airspeedswift/swift
test/Sema/enum_conformance_synthesis.swift
3
12063
// RUN: %target-swift-frontend -typecheck -verify -primary-file %s %S/Inputs/enum_conformance_synthesis_other.swift -verify-ignore-unknown -swift-version 4 var hasher = Hasher() enum Foo: CaseIterable { case A, B } func foo() { if Foo.A == .B { } var _: Int = Foo.A.hashValue Foo.A.hash(into: &hasher) _ = Foo.allCases Foo.A == Foo.B // expected-warning {{result of operator '==' is unused}} } enum Generic<T>: CaseIterable { case A, B static func method() -> Int { // Test synthesis of == without any member lookup being done if A == B { } return Generic.A.hashValue } } func generic() { if Generic<Foo>.A == .B { } var _: Int = Generic<Foo>.A.hashValue Generic<Foo>.A.hash(into: &hasher) _ = Generic<Foo>.allCases } func localEnum() -> Bool { enum Local { case A, B } return Local.A == .B } enum CustomHashable { case A, B func hash(into hasher: inout Hasher) {} } func ==(x: CustomHashable, y: CustomHashable) -> Bool { return true } func customHashable() { if CustomHashable.A == .B { } var _: Int = CustomHashable.A.hashValue CustomHashable.A.hash(into: &hasher) } // We still synthesize conforming overloads of '==' and 'hashValue' if // explicit definitions don't satisfy the protocol requirements. Probably // not what we actually want. enum InvalidCustomHashable { case A, B var hashValue: String { return "" } // expected-error {{invalid redeclaration of synthesized implementation for protocol requirement 'hashValue'}} } func ==(x: InvalidCustomHashable, y: InvalidCustomHashable) -> String { return "" } func invalidCustomHashable() { if InvalidCustomHashable.A == .B { } var s: String = InvalidCustomHashable.A == .B s = InvalidCustomHashable.A.hashValue _ = s var _: Int = InvalidCustomHashable.A.hashValue InvalidCustomHashable.A.hash(into: &hasher) } // Check use of an enum's synthesized members before the enum is actually declared. struct UseEnumBeforeDeclaration { let eqValue = EnumToUseBeforeDeclaration.A == .A let hashValue = EnumToUseBeforeDeclaration.A.hashValue } enum EnumToUseBeforeDeclaration { case A } func getFromOtherFile() -> AlsoFromOtherFile { return .A } func overloadFromOtherFile() -> YetAnotherFromOtherFile { return .A } func overloadFromOtherFile() -> Bool { return false } func useEnumBeforeDeclaration() { // Check enums from another file in the same module. if FromOtherFile.A == .A {} let _: Int = FromOtherFile.A.hashValue if .A == getFromOtherFile() {} if .A == overloadFromOtherFile() {} } // Complex enums are not automatically Equatable, Hashable, or CaseIterable. enum Complex { case A(Int) case B } func complex() { if Complex.A(1) == .B { } // expected-error{{cannot convert value of type 'Complex' to expected argument type 'CustomHashable'}} } // Enums with equatable payloads are equatable if they explicitly conform. enum EnumWithEquatablePayload: Equatable { case A(Int) case B(String, Int) case C } func enumWithEquatablePayload() { if EnumWithEquatablePayload.A(1) == .B("x", 1) { } if EnumWithEquatablePayload.A(1) == .C { } if EnumWithEquatablePayload.B("x", 1) == .C { } } // Enums with hashable payloads are hashable if they explicitly conform. enum EnumWithHashablePayload: Hashable { case A(Int) case B(String, Int) case C } func enumWithHashablePayload() { _ = EnumWithHashablePayload.A(1).hashValue _ = EnumWithHashablePayload.B("x", 1).hashValue _ = EnumWithHashablePayload.C.hashValue EnumWithHashablePayload.A(1).hash(into: &hasher) EnumWithHashablePayload.B("x", 1).hash(into: &hasher) EnumWithHashablePayload.C.hash(into: &hasher) // ...and they should also inherit equatability from Hashable. if EnumWithHashablePayload.A(1) == .B("x", 1) { } if EnumWithHashablePayload.A(1) == .C { } if EnumWithHashablePayload.B("x", 1) == .C { } } // Enums with non-hashable payloads don't derive conformance. struct NotHashable {} enum EnumWithNonHashablePayload: Hashable { // expected-error 2 {{does not conform}} case A(NotHashable) //expected-note {{associated value type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'EnumWithNonHashablePayload' to 'Hashable'}} // expected-note@-1 {{associated value type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'EnumWithNonHashablePayload' to 'Equatable'}} } // Enums should be able to derive conformances based on the conformances of // their generic arguments. enum GenericHashable<T: Hashable>: Hashable { case A(T) case B } func genericHashable() { if GenericHashable<String>.A("a") == .B { } var _: Int = GenericHashable<String>.A("a").hashValue } // But it should be an error if the generic argument doesn't have the necessary // constraints to satisfy the conditions for derivation. enum GenericNotHashable<T: Equatable>: Hashable { // expected-error 2 {{does not conform to protocol 'Hashable'}} case A(T) //expected-note 2 {{associated value type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'GenericNotHashable<T>' to 'Hashable'}} case B } func genericNotHashable() { if GenericNotHashable<String>.A("a") == .B { } let _: Int = GenericNotHashable<String>.A("a").hashValue // No error. hashValue is always synthesized, even if Hashable derivation fails GenericNotHashable<String>.A("a").hash(into: &hasher) // expected-error {{value of type 'GenericNotHashable<String>' has no member 'hash'}} } // An enum with no cases should also derive conformance. enum NoCases: Hashable {} // rdar://19773050 private enum Bar<T> { case E(Unknown<T>) // expected-error {{cannot find type 'Unknown' in scope}} mutating func value() -> T { switch self { // FIXME: Should diagnose here that '.' needs to be inserted, but E has an ErrorType at this point case E(let x): return x.value } } } // Equatable extension -- rdar://20981254 enum Instrument { case Piano case Violin case Guitar } extension Instrument : Equatable {} extension Instrument : CaseIterable {} enum UnusedGeneric<T> { case a, b, c } extension UnusedGeneric : CaseIterable {} // Explicit conformance should work too public enum Medicine { case Antibiotic case Antihistamine } extension Medicine : Equatable {} public func ==(lhs: Medicine, rhs: Medicine) -> Bool { return true } // No explicit conformance; but it can be derived, for the same-file cases. enum Complex2 { case A(Int) case B } extension Complex2 : Hashable {} extension Complex2 : CaseIterable {} // expected-error {{type 'Complex2' does not conform to protocol 'CaseIterable'}} extension FromOtherFile: CaseIterable {} // expected-error {{cannot be automatically synthesized in an extension in a different file to the type}} extension CaseIterableAcrossFiles: CaseIterable { public static var allCases: [CaseIterableAcrossFiles] { return [ .A ] } } // No explicit conformance and it cannot be derived. enum NotExplicitlyHashableAndCannotDerive { case A(NotHashable) //expected-note {{associated value type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Hashable'}} // expected-note@-1 {{associated value type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Equatable'}} } extension NotExplicitlyHashableAndCannotDerive : Hashable {} // expected-error 2 {{does not conform}} extension NotExplicitlyHashableAndCannotDerive : CaseIterable {} // expected-error {{does not conform}} // Verify that conformance (albeit manually implemented) can still be added to // a type in a different file. extension OtherFileNonconforming: Hashable { static func ==(lhs: OtherFileNonconforming, rhs: OtherFileNonconforming) -> Bool { return true } func hash(into hasher: inout Hasher) {} } // ...but synthesis in a type defined in another file doesn't work yet. extension YetOtherFileNonconforming: Equatable {} // expected-error {{cannot be automatically synthesized in an extension in a different file to the type}} extension YetOtherFileNonconforming: CaseIterable {} // expected-error {{does not conform}} // Verify that an indirect enum doesn't emit any errors as long as its "leaves" // are conformant. enum StringBinaryTree: Hashable { indirect case tree(StringBinaryTree, StringBinaryTree) case leaf(String) } // Add some generics to make it more complex. enum BinaryTree<Element: Hashable>: Hashable { indirect case tree(BinaryTree, BinaryTree) case leaf(Element) } // Verify mutually indirect enums. enum MutuallyIndirectA: Hashable { indirect case b(MutuallyIndirectB) case data(Int) } enum MutuallyIndirectB: Hashable { indirect case a(MutuallyIndirectA) case data(Int) } // Verify that it works if the enum itself is indirect, rather than the cases. indirect enum TotallyIndirect: Hashable { case another(TotallyIndirect) case end(Int) } // Check the use of conditional conformances. enum ArrayOfEquatables : Equatable { case only([Int]) } struct NotEquatable { } enum ArrayOfNotEquatables : Equatable { // expected-error{{type 'ArrayOfNotEquatables' does not conform to protocol 'Equatable'}} case only([NotEquatable]) //expected-note {{associated value type '[NotEquatable]' does not conform to protocol 'Equatable', preventing synthesized conformance of 'ArrayOfNotEquatables' to 'Equatable'}} } // Conditional conformances should be able to be synthesized enum GenericDeriveExtension<T> { case A(T) } extension GenericDeriveExtension: Equatable where T: Equatable {} extension GenericDeriveExtension: Hashable where T: Hashable {} // Incorrectly/insufficiently conditional shouldn't work enum BadGenericDeriveExtension<T> { case A(T) //expected-note {{associated value type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Hashable'}} //expected-note@-1 {{associated value type 'T' does not conform to protocol 'Equatable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Equatable'}} } extension BadGenericDeriveExtension: Equatable {} // // expected-error@-1 {{type 'BadGenericDeriveExtension<T>' does not conform to protocol 'Equatable'}} extension BadGenericDeriveExtension: Hashable where T: Equatable {} // expected-error@-1 {{type 'BadGenericDeriveExtension' does not conform to protocol 'Hashable'}} // But some cases don't need to be conditional, even if they look similar to the // above struct AlwaysHashable<T>: Hashable {} enum UnusedGenericDeriveExtension<T> { case A(AlwaysHashable<T>) } extension UnusedGenericDeriveExtension: Hashable {} // Cross-file synthesis is disallowed for conditional cases just as it is for // non-conditional ones. extension GenericOtherFileNonconforming: Equatable where T: Equatable {} // expected-error@-1{{implementation of 'Equatable' cannot be automatically synthesized in an extension in a different file to the type}} // rdar://problem/41852654 // There is a conformance to Equatable (or at least, one that implies Equatable) // in the same file as the type, so the synthesis is okay. Both orderings are // tested, to catch choosing extensions based on the order of the files, etc. protocol ImplierMain: Equatable {} enum ImpliedMain: ImplierMain { case a(Int) } extension ImpliedOther: ImplierMain {} // FIXME: Remove -verify-ignore-unknown. // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(Foo, Foo) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '<T> (Generic<T>, Generic<T>) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(InvalidCustomHashable, InvalidCustomHashable) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(EnumToUseBeforeDeclaration, EnumToUseBeforeDeclaration) -> Bool'
apache-2.0
7845942bc6b8f584b9adacf6a6829af2
34.584071
209
0.738208
4.029058
false
false
false
false
PlanTeam/BSON
Sources/BSON/Types/Optional.swift
1
583
extension Optional where Wrapped == Primitive { public subscript(key: String) -> Primitive? { get { return (self as? Document)?[key] } set { var document = (self as? Document) ?? [:] document[key] = newValue self = document } } public subscript(index: Int) -> Primitive { get { return (self as! Document)[index] } set { var document = self as! Document document[index] = newValue self = document } } }
mit
218a988968efde0207337eab58299348
24.347826
53
0.475129
4.89916
false
false
false
false
headione/criticalmaps-ios
CriticalMapsKit/Sources/SharedModels/CoordinatieRegion.swift
1
875
import CoreLocation import Foundation import MapKit /// A structure for region data public struct CoordinateRegion: Equatable { public var center: CLLocationCoordinate2D public var span: MKCoordinateSpan public init( center: CLLocationCoordinate2D, span: MKCoordinateSpan ) { self.center = center self.span = span } public init(coordinateRegion: MKCoordinateRegion) { self.center = coordinateRegion.center self.span = coordinateRegion.span } public var asMKCoordinateRegion: MKCoordinateRegion { .init(center: self.center, span: self.span) } public static func == (lhs: Self, rhs: Self) -> Bool { lhs.center.latitude == rhs.center.latitude && lhs.center.longitude == rhs.center.longitude && lhs.span.latitudeDelta == rhs.span.latitudeDelta && lhs.span.longitudeDelta == rhs.span.longitudeDelta } }
mit
4a1c553fa680d9d34696d7511524f2d4
25.515152
59
0.716571
4.464286
false
false
false
false