repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tranhieutt/Swiftz | refs/heads/master | Swiftz/JSON.swift | bsd-3-clause | 1 | //
// JSON.swift
// Swiftz
//
// Created by Maxwell Swadling on 5/06/2014.
// Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//
import Foundation
public enum JSONValue : CustomStringConvertible {
case JSONArray([JSONValue])
case JSONObject(Dictionary<String, JSONValue>)
case JSONNumber(Double)
case JSONString(String)
case JSONBool(Bool)
case JSONNull()
private func values() -> NSObject {
switch self {
case let .JSONArray(xs):
return NSArray(array: xs.map { $0.values() })
case let .JSONObject(xs):
return Dictionary.fromList(xs.map({ k, v in
return (NSString(string: k), v.values())
}))
case let .JSONNumber(n):
return NSNumber(double: n)
case let .JSONString(s):
return NSString(string: s)
case let .JSONBool(b):
return NSNumber(bool: b)
case .JSONNull():
return NSNull()
}
}
// we know this is safe because of the NSJSONSerialization docs
private static func make(a : NSObject) -> JSONValue {
switch a {
case let xs as NSArray:
return .JSONArray((xs as [AnyObject]).map { self.make($0 as! NSObject) })
case let xs as NSDictionary:
return JSONValue.JSONObject(Dictionary.fromList((xs as [NSObject: AnyObject]).map({ (k: NSObject, v: AnyObject) in
return (String(k as! NSString), self.make(v as! NSObject))
})))
case let xs as NSNumber: // TODO: number or bool?...
return .JSONNumber(Double(xs.doubleValue))
case let xs as NSString:
return .JSONString(String(xs))
case _ as NSNull:
return .JSONNull()
default:
return error("Non-exhaustive pattern match performed.");
}
}
public func encode() -> NSData? {
do {
// TODO: check s is a dict or array
return try NSJSONSerialization.dataWithJSONObject(self.values(), options: NSJSONWritingOptions(rawValue: 0))
} catch _ {
return nil
}
}
// TODO: should this be optional?
public static func decode(s : NSData) -> JSONValue? {
let r : AnyObject?
do {
r = try NSJSONSerialization.JSONObjectWithData(s, options: NSJSONReadingOptions(rawValue: 0))
} catch _ {
r = nil
}
if let json: AnyObject = r {
return make(json as! NSObject)
} else {
return .None
}
}
public static func decode(s : String) -> JSONValue? {
return JSONValue.decode(s.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)
}
public var description : String {
get {
switch self {
case .JSONNull():
return "JSONNull()"
case let .JSONBool(b):
return "JSONBool(\(b))"
case let .JSONString(s):
return "JSONString(\(s))"
case let .JSONNumber(n):
return "JSONNumber(\(n))"
case let .JSONObject(o):
return "JSONObject(\(o))"
case let .JSONArray(a):
return "JSONArray(\(a))"
}
}
}
}
// you'll have more fun if you match tuples
// Equatable
public func ==(lhs : JSONValue, rhs : JSONValue) -> Bool {
switch (lhs, rhs) {
case (.JSONNull(), .JSONNull()):
return true
case let (.JSONBool(l), .JSONBool(r)) where l == r:
return true
case let (.JSONString(l), .JSONString(r)) where l == r:
return true
case let (.JSONNumber(l), .JSONNumber(r)) where l == r:
return true
case let (.JSONObject(l), .JSONObject(r))
where l.elementsEqual(r, isEquivalent: { (v1: (String, JSONValue), v2: (String, JSONValue)) in v1.0 == v2.0 && v1.1 == v2.1 }):
return true
case let (.JSONArray(l), .JSONArray(r)) where l.elementsEqual(r, isEquivalent: { $0 == $1 }):
return true
default:
return false
}
}
public func !=(lhs : JSONValue, rhs : JSONValue) -> Bool {
return !(lhs == rhs)
}
// someday someone will ask for this
//// Comparable
//func <=(lhs: JSValue, rhs: JSValue) -> Bool {
// return false;
//}
//
//func >(lhs: JSValue, rhs: JSValue) -> Bool {
// return !(lhs <= rhs)
//}
//
//func >=(lhs: JSValue, rhs: JSValue) -> Bool {
// return (lhs > rhs || lhs == rhs)
//}
//
//func <(lhs: JSValue, rhs: JSValue) -> Bool {
// return !(lhs >= rhs)
//}
public func <? <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> A? {
switch lhs {
case let .JSONObject(d):
return resolveKeypath(d, rhs: rhs).flatMap(A.fromJSON)
default:
return .None
}
}
public func <? <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> [A]? {
switch lhs {
case let .JSONObject(d):
return resolveKeypath(d, rhs: rhs).flatMap(JArrayFrom<A, A>.fromJSON)
default:
return .None
}
}
public func <? <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> [String:A]? {
switch lhs {
case let .JSONObject(d):
return resolveKeypath(d, rhs: rhs).flatMap(JDictionaryFrom<A, A>.fromJSON)
default:
return .None
}
}
public func <! <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> A {
if let r : A = (lhs <? rhs) {
return r
}
return error("Cannot find value at keypath \(rhs) in JSON object \(rhs).")
}
public func <! <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> [A] {
if let r : [A] = (lhs <? rhs) {
return r
}
return error("Cannot find array at keypath \(rhs) in JSON object \(rhs).")
}
public func <! <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> [String:A] {
if let r : [String:A] = (lhs <? rhs) {
return r
}
return error("Cannot find object at keypath \(rhs) in JSON object \(rhs).")
}
// traits
public protocol JSONDecodable {
typealias J = Self
static func fromJSON(x : JSONValue) -> J?
}
public protocol JSONEncodable {
typealias J
static func toJSON(x : J) -> JSONValue
}
// J mate
public protocol JSON : JSONDecodable, JSONEncodable { }
// instances
extension Bool : JSON {
public static func fromJSON(x : JSONValue) -> Bool? {
switch x {
case let .JSONBool(n):
return n
case .JSONNumber(0):
return false
case .JSONNumber(1):
return true
default:
return Optional.None
}
}
public static func toJSON(xs : Bool) -> JSONValue {
return JSONValue.JSONNumber(Double(xs))
}
}
extension Int : JSON {
public static func fromJSON(x : JSONValue) -> Int? {
switch x {
case let .JSONNumber(n):
return Int(n)
default:
return Optional.None
}
}
public static func toJSON(xs : Int) -> JSONValue {
return JSONValue.JSONNumber(Double(xs))
}
}
extension Double : JSON {
public static func fromJSON(x : JSONValue) -> Double? {
switch x {
case let .JSONNumber(n):
return n
default:
return Optional.None
}
}
public static func toJSON(xs : Double) -> JSONValue {
return JSONValue.JSONNumber(xs)
}
}
extension NSNumber : JSON {
public class func fromJSON(x : JSONValue) -> NSNumber? {
switch x {
case let .JSONNumber(n):
return NSNumber(double: n)
default:
return Optional.None
}
}
public class func toJSON(xs : NSNumber) -> JSONValue {
return JSONValue.JSONNumber(Double(xs))
}
}
extension String : JSON {
public static func fromJSON(x : JSONValue) -> String? {
switch x {
case let .JSONString(n):
return n
default:
return Optional.None
}
}
public static func toJSON(xs : String) -> JSONValue {
return JSONValue.JSONString(xs)
}
}
// or unit...
extension NSNull : JSON {
public class func fromJSON(x : JSONValue) -> NSNull? {
switch x {
case .JSONNull():
return NSNull()
default:
return Optional.None
}
}
public class func toJSON(xs : NSNull) -> JSONValue {
return JSONValue.JSONNull()
}
}
// container types should be split
public struct JArrayFrom<A, B : JSONDecodable where B.J == A> : JSONDecodable {
public typealias J = [A]
public static func fromJSON(x : JSONValue) -> J? {
switch x {
case let .JSONArray(xs):
let r = xs.map(B.fromJSON)
let rp = mapFlatten(r)
if r.count == rp.count {
return rp
} else {
return nil
}
default:
return Optional.None
}
}
}
public struct JArrayTo<A, B : JSONEncodable where B.J == A> : JSONEncodable {
public typealias J = [A]
public static func toJSON(xs: J) -> JSONValue {
return JSONValue.JSONArray(xs.map(B.toJSON))
}
}
public struct JArray<A, B : JSON where B.J == A> : JSON {
public typealias J = [A]
public static func fromJSON(x : JSONValue) -> J? {
switch x {
case let .JSONArray(xs):
let r = xs.map(B.fromJSON)
let rp = mapFlatten(r)
if r.count == rp.count {
return rp
} else {
return nil
}
default:
return Optional.None
}
}
public static func toJSON(xs : J) -> JSONValue {
return JSONValue.JSONArray(xs.map(B.toJSON))
}
}
public struct JDictionaryFrom<A, B : JSONDecodable where B.J == A> : JSONDecodable {
public typealias J = Dictionary<String, A>
public static func fromJSON(x : JSONValue) -> J? {
switch x {
case let .JSONObject(xs):
return Dictionary.fromList(xs.map({ k, x in
return (k, B.fromJSON(x)!)
}))
default:
return Optional.None
}
}
}
public struct JDictionaryTo<A, B : JSONEncodable where B.J == A> : JSONEncodable {
public typealias J = Dictionary<String, A>
public static func toJSON(xs : J) -> JSONValue {
return JSONValue.JSONObject(Dictionary.fromList(xs.map({ k, x -> (String, JSONValue) in
return (k, B.toJSON(x))
})))
}
}
public struct JDictionary<A, B : JSON where B.J == A> : JSON {
public typealias J = Dictionary<String, A>
public static func fromJSON(x : JSONValue) -> J? {
switch x {
case let .JSONObject(xs):
return Dictionary<String, A>.fromList(xs.map({ k, x in
return (k, B.fromJSON(x)!)
}))
default:
return Optional.None
}
}
public static func toJSON(xs : J) -> JSONValue {
return JSONValue.JSONObject(Dictionary.fromList(xs.map({ k, x in
return (k, B.toJSON(x))
})))
}
}
/// MARK: Implementation Details
private func resolveKeypath(lhs : Dictionary<String, JSONValue>, rhs : JSONKeypath) -> JSONValue? {
if rhs.path.isEmpty {
return .None
}
switch rhs.path.match {
case .Nil:
return .None
case let .Cons(hd, tl):
if let o = lhs[hd] {
switch o {
case let .JSONObject(d) where rhs.path.count > 1:
return resolveKeypath(d, rhs: JSONKeypath(tl))
default:
return o
}
}
return .None
}
}
| 5a5e672bfea5931ea39ab7c12247f35e | 22.152778 | 129 | 0.65077 | false | false | false | false |
Rostmen/TimelineController | refs/heads/master | RZTimelineCollection/Extensions.swift | apache-2.0 | 1 | //
// Extensions.swift
// RZTimelineCollection
//
// Created by Rostyslav Kobizsky on 12/18/14.
// Copyright (c) 2014 Rozdoum. All rights reserved.
//
import UIKit
extension UIDevice {
class func rz_isCurrentDeviceBeforeiOS8() -> Bool {
let systemVersion = UIDevice.currentDevice().systemVersion as NSString
return systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedAscending
}
}
extension UIView {
func rz_pinSubview(subview: UIView, toEdge attribute: NSLayoutAttribute) {
self.addConstraint(NSLayoutConstraint(
item: self,
attribute: attribute,
relatedBy: NSLayoutRelation.Equal,
toItem: subview,
attribute: attribute,
multiplier: 1,
constant: 0))
}
func rz_pinAllEdgesOfSubview(subview: UIView) {
self.rz_pinSubview(subview, toEdge: NSLayoutAttribute.Bottom)
self.rz_pinSubview(subview, toEdge: NSLayoutAttribute.Top)
self.rz_pinSubview(subview, toEdge: NSLayoutAttribute.Leading)
self.rz_pinSubview(subview, toEdge: NSLayoutAttribute.Trailing)
}
}
extension UIFont {
func rectOfString (string: NSString, constrainedToWidth width: CGFloat) -> CGRect {
let combinedOptions = NSObject.combine(.UsesLineFragmentOrigin, with: .UsesFontLeading)
return string.boundingRectWithSize(
CGSize(width: width, height: CGFloat.max),
options: combinedOptions,
attributes: [NSFontAttributeName : self],
context: nil)
}
}
extension UIColor {
func darkeningColorWithValue(value: CGFloat) -> UIColor {
let totalComponents = CGColorGetNumberOfComponents(CGColor)
let isGreyscale = totalComponents == 2 ? true : false
let oldComponents = CGColorGetComponents(CGColor)
var newComponents: [CGFloat] = [0, 0, 0, 0]
if isGreyscale {
newComponents[0] = oldComponents[0] - value < 0 ? 0 : oldComponents[0] - value
newComponents[1] = oldComponents[0] - value < 0 ? 0 : oldComponents[0] - value
newComponents[2] = oldComponents[0] - value < 0 ? 0 : oldComponents[0] - value
newComponents[3] = oldComponents[1]
} else {
newComponents[0] = oldComponents[0] - value < 0 ? 0 : oldComponents[0] - value
newComponents[1] = oldComponents[1] - value < 0 ? 0 : oldComponents[1] - value
newComponents[2] = oldComponents[2] - value < 0 ? 0 : oldComponents[2] - value
newComponents[3] = oldComponents[3]
}
let colorSpace = CGColorSpaceCreateDeviceRGB()
let newColor = CGColorCreate(colorSpace, newComponents)
return UIColor(CGColor: newColor)
}
}
extension UIImage {
func rz_imageMaskedWithColor(color: UIColor) -> UIImage {
let imageRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(imageRect.size, false, self.scale)
let context = UIGraphicsGetCurrentContext()
CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0, -(imageRect.size.height));
CGContextClipToMask(context, imageRect, CGImage);
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, imageRect);
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
class func rz_postImageFromBundleWithName(name: String) -> UIImage? {
return UIImage(named: "RZPostAssets.bundle/Images/\(name)")
}
class func rz_postRegularImage() -> UIImage? {
return UIImage.rz_postImageFromBundleWithName("bubble_regular")
}
class func rz_postRegularTaillessImage() -> UIImage? {
return UIImage.rz_postImageFromBundleWithName("bubble_tailless")
}
class func rz_postRegularStrokedImage() -> UIImage? {
return UIImage.rz_postImageFromBundleWithName("bubble_stroked")
}
class func rz_postRegularStrokedTaillessImage() -> UIImage? {
return UIImage.rz_postImageFromBundleWithName("bubble_stroked_tailless")
}
class func rz_postCompactImage() -> UIImage? {
return UIImage.rz_postImageFromBundleWithName("bubble_min")
}
class func rz_postCompactTaillessImage() -> UIImage? {
return UIImage.rz_postImageFromBundleWithName("bubble_min_tailless")
}
class func rz_defaultAccessoryImage() -> UIImage? {
return UIImage.rz_postImageFromBundleWithName("clip")
}
class func rz_defaultTypingIndicatorImage() -> UIImage? {
return UIImage.rz_postImageFromBundleWithName("typing")
}
class func rz_defaultPlayImage() -> UIImage? {
return UIImage.rz_postImageFromBundleWithName("play")
}
func rz_imageWithOrientation(orientation: UIImageOrientation) -> UIImage {
return UIImage(CGImage: CGImage, scale: scale, orientation: orientation)!
}
} | a057cbbb0fa7b3379abc67a1bcf073fa | 36.474453 | 131 | 0.660432 | false | false | false | false |
heitara/swift-3 | refs/heads/master | playgrounds/Lecture6.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
/*
Какво е playground?
Това вид проект, който се изпозлва от xCode. Интерактивно показва какво е състоянието на паметта на компютъра във всеки един ред на изпълнение на код-а. Позволява лесно онагледяване на примерния код. Много по-лесно може да се анализира кода. Можем да скицираме проблеми и техните решения, които да използваме за напред.
*/
//: # Лекция 6: Класове (и Структури)
//: ## курс: Увод в прогрмаирането със Swift
//: ### Структури и изчислими пропъртита; Read–only пропъртита
struct Merchandise {
var name: String = "Noname - Merchandise"
var pricePerUnit: Double = 0.0
var isAvailable: Bool = false
static func printInfo(merchandise:Merchandise) {
print("[Static] Product : \(merchandise.name) - \(merchandise.pricePerUnit) - \(merchandise.isAvailable ? "available" : "unavailable")")
//Тук self реферира към типа на структурата т.е. Merchandise3
//print("Struct type: \(self)") //
}
func printInfoName(name:String = "What???") {
print("[Info] Product : \(self.name) - \(pricePerUnit) - \(isAvailable ? "available" : "unavailable")")
}
}
//var m = Merchandise()
//m.printInfoName(name:
//Merchandise.
extension Merchandise {
// var x: Int;
//изчислими пропъртита
var incomePerUnit:Double {
//гетър
get {
return self.pricePerUnit * 0.2
}
}
var realPricePerUnit:Double {
//гетър
get {
return self.pricePerUnit * 0.8
}
//сетър
set (newValue) {
self.pricePerUnit = newValue * 1.25
}
}
//съкратен вариант
var realPricePerUnitShort:Double {
get {
return self.pricePerUnit * 0.8
}
set {
self.pricePerUnit = newValue * 1.25
}
}
//read-only - съкратен вариант
var incomePerUnitShort:Double {
return self.pricePerUnit * 0.2
}
}
//: #### Пример за константно свързване (константа) когато типът има променливи пропъртита
let g1 = Merchandise()
//g1.name = "New name" //note: change 'let' to 'var' to make it mutable
print("----computed properties----")
var macBookPro = Merchandise(name:"MacBook Pro 15\"", pricePerUnit: 5800.0, isAvailable: true)
Merchandise.printInfo(merchandise: macBookPro)
print("Income per product: \(macBookPro.incomePerUnit)")
print("Real price per product: \(macBookPro.realPricePerUnit)")
macBookPro.realPricePerUnit = 5800 - macBookPro.incomePerUnit
print("Real price per product: \(macBookPro.realPricePerUnit)")
//: ### мързеливи пропъртита
struct LazyStruct {
var count: Int
init (count:Int) {
print("\(LazyStruct.self) се конструира чрез -> \(#function)")
self.count = count
}
}
struct ExampleLazyProperty {
lazy var lazyProp:LazyStruct = LazyStruct(count: 5)
var regularInt = 5
init() {
print("\(ExampleLazyProperty.self) се конструира чрез -> \(#function)")
}
init(regularInt:Int) {
self.regularInt = regularInt
print("\(ExampleLazyProperty.self) се конструира чрез -> \(#function)")
}
mutating func increment(with: Int) {
self = ExampleLazyProperty(regularInt: self.regularInt + with)
}
}
var lazyPropExample = ExampleLazyProperty()
lazyPropExample.regularInt = 15
print("")
print("")
print("")
print("Стойноста в нормалното пропърти 'regularInt' e \(lazyPropExample.regularInt)")
print("Стойноста на мързеливото пропърти е \(lazyPropExample.lazyProp.count)")
print("Стойноста в нормалното пропърти 'regularInt' е \(lazyPropExample.regularInt)")
print("")
print("")
print("")
//: ## Kласове
class Media {
var name: String = ""
var sizeInBytes: Double = 0.0
}
//: ### порменлива
var movie = Media()
movie.name = "X-Men"
print("Media name: \(movie.name)")
let ref = movie
//let ref = Media()
print("Media ref name: \(ref.name)")
movie.name = "X-Men 2"
print("Media ref name: \(ref.name)")
print("Media movie name: \(movie.name)")
//: ### Разликите между референтни типове и стойностни типове
struct MediaList {
let item: Media = Media()
var count = 1
}
let mediaList = MediaList()
let newMediaList = mediaList
print("Media ref name: \(mediaList.item.name)")
mediaList.item.name = "new name"
//предизвиква грешка
//mediaList.count = 5
print("Media ref name: \(mediaList.item.name)")
newMediaList.item.name = "new media list"
print("Media ref name: \(mediaList.item.name)")
var newMediaList2 = mediaList
//това работи, понеже newMediaList2 е променлива
newMediaList2.count = 5
//това също работи
newMediaList2.item.name = "X-Men 2.5"
let constMediaList = mediaList
//това също работи
constMediaList.item.name = "X-Men 3"
print("")
print("")
print("")
//: ## Предаване по стойност (Value types)
var a = 1
var b = a
print("Initial values:")
print("a = \(a)")
print("b = \(b)")
a += 5
print("Modify a += 5.")
print("a = \(a)")
print("b = \(b)")
//func modify(/*let*/ value:Int) {
// value = 3
//}
func modify(value:inout Int) {
value = 3
}
print("Example with functions.")
print("b = \(b)")
modify(value: &b)
print("Modify b = 3.")
print("b = \(b)")
//: ## Предаване по референция (reference types)
//TODO:
//: ## Наследяване
//: Какво е базов клас?
//: - Note:
//: В Swift, ако не е посочен базов клас в клас дефинирани от нас, то няма подразбиращ се базов клас от който всички типове произхождат. Разлика с Java - ```Object``` (https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html).
enum Color {
case pink
case green
case black
case blue
case white
case noColor
}
class Show {
var name: String
var color: Color
var country: String
var language: String
var duration: Double
// init(name:String) {
// self.name = name
// color = .noColor
// self.country = "no country"
// language = "BG"
// duration = 0.0
// }
init() {
self.name = " no name "
color = .noColor
self.country = "no country"
language = "BG"
duration = 0.0
}
// convenience init() {
// self.init(name: "No name")
// }
var durationInMinutes:String {
let minutes:Int = Int(round(duration))
let minutesInHour = 60
return "\(minutes / minutesInHour) : \(minutes % minutesInHour) min"
}
func shortDescription() -> String {
return "\(name) - \(language) : Duration: \(durationInMinutes)"
}
deinit {
print("deinit \(#function)" )
}
}
extension Show {
convenience init(name:String, duration:Double) {
self.init()
self.name = name
self.duration = duration
}
// convenience init(name:String) {
// self.init()
// self.name = name
// }
}
class TVShow : Show {
var series:Int
//var duration: Double;
override init() {
series = 0
//извиква конструиращия метод на бащиния клас
// super.init(name:"TVSHOW")
// super.init(name: name, country: "no countrye")
}
init(name:String) {
series = 0
super.init()
super.name = name
//извиква конструиращия метод на бащиния клас
// super.init(name:name)
// super.init(name: name, country: "no countrye")
}
// convenience init() {
// self.init(name: "no name")
// }
var isTurkish:Bool {
return self.language == "TR" && self.series > 100
}
override func shortDescription() -> String {
return super.shortDescription() + " v.2"
}
deinit {
print("deinit TVShow" )
}
}
//extension TVShow:Show {
//
//}
var blackSails:TVShow = TVShow(name: "Balck Sails", duration: 123)
//var blackSails:TVShow = TVShow()
//blackSails.duration = 134
print("")
print("")
print("")
print("")
print(blackSails.shortDescription())
blackSails = TVShow()
//: Как дефинираме, че даден клас е наследник на друг и какво означава това?
//: Наследяване на произволно ниво. Какво ни носи това?
//: Предефиниране (overriding)
//: Достъп до базовите методи, пропъртита и subscript-s, става чрез ```super```
//: - Note:
//: В Swift, изпозлваме запазената дума ```override``` за да обозначим, че предефинираме дадена функци, пропърти (get & set).
//: Можем да обявим функция или пропърти, че няма да се променят. За целта използваме ```final```.
//: Можем да обявим дори и цял клас. ```final class``` - класът няма да може да бъде наследяван.
//: Инициализатори (init методи)
struct StructBook {
var pageCount = 0
var title = "no title"
var publishDate:Date? = nil
}
class Book {
var pageCount = 0
var title = "no title"
var publishDate:Date? = nil
convenience init(pages:Int) {
self.init()
self.pageCount = pages
}
convenience init(pages:Int, title:String) {
self.init(pages:pages)
self.title = title
}
}
extension Book {
convenience init(title:String) {
self.init()
self.title = title
}
convenience init(pages:Int, title:String, date: Date?) {
self.init(pages:pages, title:title)
self.publishDate = date
}
}
var book = Book()
book.pageCount = 100
var book100 = Book(pages: 100)
var book2 = StructBook(pageCount: 1000, title: "Swift 3", publishDate: nil)
//: ## Задачи:
//: ### Да се направи модел на по следното задание:
//
//Задание 1
//
//Да се имплементира мобилно приложение, което
//представя информация за времето. Времето да има две представяния
//- по целзии, по фаренхайт. Да може да се съставя списък от
//градове, който да представя информация за времето в
//определените локации.
//
//Задание 2
//
//Да се имплементира мобилно приложение, което
//представя списък от снимки, които всеки потребител може да upload-ва.
//Всеки потребител да има списък от снимки, които се формира от снимките на всички
//потребители, на които е последовател. Всеки да може да стане
//последвател на друг потребител, но да може и да се откаже да е последовател.
//Под всяка снимка потребителите да могат да коментират. Да я отбелязват като любима.
//Или да я споделят с други потребители. Всеки потребител да има списък с
//последователи. Да има вход в системата с потребителско име и парола.
| 99f78246aa7ac742d1eb189c4cf61d1c | 22.797267 | 320 | 0.632718 | false | false | false | false |
ben-ng/swift | refs/heads/master | test/stdlib/IntervalTraps.swift | apache-2.0 | 1 | //===--- IntervalTraps.swift ----------------------------------------------===//
//
// 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: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-build-swift %s -o %t/a.out_Debug
// RUN: %target-build-swift %s -o %t/a.out_Release -O
//
// RUN: %target-run %t/a.out_Debug
// RUN: %target-run %t/a.out_Release
// REQUIRES: executable_test
import StdlibUnittest
let testSuiteSuffix = _isDebugAssertConfiguration() ? "_debug" : "_release"
var IntervalTraps = TestSuite("IntervalTraps" + testSuiteSuffix)
IntervalTraps.test("HalfOpen")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
var interval = 1.0..<1.0
// FIXME: the plan is for floating point numbers to no longer be
// strideable; then this will drop the "OfStrideable"
expectType(Range<Double>.self, &interval)
expectCrashLater()
_ = 1.0..<0.0
}
IntervalTraps.test("Closed")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
var interval = 1.0...1.0
// FIXME: the plan is for floating point numbers to no longer be
// strideable; then this will drop the "OfStrideable"
expectType(ClosedRange<Double>.self, &interval)
expectCrashLater()
_ = 1.0...0.0
}
runAllTests()
| 2e25f21376620d7e608b81c882294b7a | 30.8 | 80 | 0.640938 | false | true | false | false |
courteouselk/Relations | refs/heads/master | Tests/RelationsTests/WeakNaryTests+File.swift | mit | 1 | //
// WeakNaryTests+File.swift
// Relations
//
// Created by Anton Bronnikov on 06/01/2017.
// Copyright © 2017 Anton Bronnikov. All rights reserved.
//
import Relations
extension WeakNaryTests {
final class File : Equatable, CustomStringConvertible {
static func == (lhs: File, rhs: File) -> Bool {
return lhs === rhs
}
var description: String {
return name
}
let name: String
private (set) var _folder: WeakNto1Relation<File, Folder>! = nil
var folder: Folder? {
get {
assert(_folder.object == _folder.first)
return _folder.object
}
set {
_folder.assign(relation: newValue)
}
}
var flatFolder: [Folder] { return _folder.map({ $0 }) }
var count: Int { return _folder.count }
var underestimatedCount: Int { return _folder.underestimatedCount }
var notificationsCount = 0
var folderNameOnLatestNotification = ""
private func folderDidChange() {
notificationsCount += 1
folderNameOnLatestNotification = folder?.name ?? ""
}
init(name: String) {
self.name = name
_folder = WeakNto1Relation(this: self, getCounterpart: { $0._files }, didChange: { [unowned self] in self.folderDidChange() })
}
func removeFromFolder() {
_folder.flush()
}
}
}
| 9722ea32ae04f2625d6cfa13a104fba9 | 23.483871 | 138 | 0.543478 | false | true | false | false |
onebytecode/krugozor-iOSVisitors | refs/heads/develop | krugozor-visitorsApp/DataManager.swift | apache-2.0 | 1 | //
// DataManager.swift
// krugozor-visitorsApp
//
// Created by Alexander Danilin on 21/10/2017.
// Copyright © 2017 oneByteCode. All rights reserved.
//
import Foundation
import RealmSwift
import SwiftyJSON
public enum DataErrors: String, Error {
case noCurrentVisior = "ERROR: No Current Visitor In DB!"
}
protocol DataManaging {
func currentVisitor () throws -> Visitor?
}
/// Manages All Data In App; Guarantees Data Relevance
class DataManager: DataManaging {
let api = APIManager()
// MARK: DataManaging Protocol
func currentVisitor() throws -> Visitor? {
let realm = try Realm()
guard let currentVisitor = realm.object(ofType: Visitor.self, forPrimaryKey: 0) else { log.error(DataErrors.noCurrentVisior.rawValue); throw DataErrors.noCurrentVisior }
return currentVisitor
}
func fetchVisitorBy(sessionToken: String, completion: @escaping ((_ visitor: Visitor?, _ error: String?) -> Void)) {
api.fetchCurrentVisitorBy(sessionToken: sessionToken) { (visitor, error) in
guard visitor != nil else { log.error(error); return completion(nil, error)}
let realm = try! Realm()
guard visitor != nil else { log.error("error"); return }
try! realm.write {
realm.add(visitor!, update: true)
completion(visitor, nil)
}
}
}
}
| 4702f2acdcec577b87b3084be4eddce5 | 29.382979 | 177 | 0.640056 | false | false | false | false |
tlax/GaussSquad | refs/heads/master | GaussSquad/Model/Keyboard/States/MKeyboardStateRoot.swift | mit | 1 | import UIKit
class MKeyboardStateRoot:MKeyboardState
{
private let previousValue:Double
private let kNeedsUpdate:Bool = true
init(previousValue:Double, editing:String)
{
self.previousValue = previousValue
super.init(
editing:editing,
needsUpdate:kNeedsUpdate)
}
override func commitState(model:MKeyboard, view:UITextView)
{
let currentValue:Double = model.lastNumber()
let currentInversed:Double = 1 / currentValue
let newValue:Double = pow(previousValue, currentInversed)
editing = model.numberAsString(scalar:newValue)
view.text = model.kEmpty
view.insertText(editing)
let currentString:String = model.numberAsString(
scalar:currentValue)
commitingDescription = "\(currentString)√ = \(editing)"
}
}
| 5104527541949a9ece4c98f41a49a2e5 | 27.612903 | 65 | 0.642616 | false | false | false | false |
jopamer/swift | refs/heads/master | test/decl/protocol/req/recursion.swift | apache-2.0 | 2 | // RUN: %target-typecheck-verify-swift
protocol SomeProtocol {
associatedtype T
}
extension SomeProtocol where T == Optional<T> { } // expected-error{{same-type constraint 'Self.T' == 'Optional<Self.T>' is recursive}}
// rdar://problem/19840527
class X<T> where T == X { // expected-error{{same-type constraint 'T' == 'X<T>' is recursive}}
// expected-error@-1{{same-type requirement makes generic parameter 'T' non-generic}}
var type: T { return Swift.type(of: self) } // expected-error{{cannot convert return expression of type 'X<T>.Type' to return type 'T'}}
}
// FIXME: The "associated type 'Foo' is not a member type of 'Self'" diagnostic
// should also become "associated type 'Foo' references itself"
protocol CircularAssocTypeDefault {
associatedtype Z = Z // expected-error{{associated type 'Z' references itself}}
// expected-note@-1{{type declared here}}
// expected-note@-2{{protocol requires nested type 'Z'; do you want to add it?}}
associatedtype Z2 = Z3
// expected-note@-1{{protocol requires nested type 'Z2'; do you want to add it?}}
associatedtype Z3 = Z2
// expected-note@-1{{protocol requires nested type 'Z3'; do you want to add it?}}
associatedtype Z4 = Self.Z4 // expected-error{{associated type 'Z4' references itself}}
// expected-note@-1{{type declared here}}
// expected-note@-2{{protocol requires nested type 'Z4'; do you want to add it?}}
associatedtype Z5 = Self.Z6
// expected-note@-1{{protocol requires nested type 'Z5'; do you want to add it?}}
associatedtype Z6 = Self.Z5
// expected-note@-1{{protocol requires nested type 'Z6'; do you want to add it?}}
}
struct ConformsToCircularAssocTypeDefault : CircularAssocTypeDefault { }
// expected-error@-1 {{type 'ConformsToCircularAssocTypeDefault' does not conform to protocol 'CircularAssocTypeDefault'}}
// rdar://problem/20000145
public protocol P {
associatedtype T
}
public struct S<A: P> where A.T == S<A> {
// expected-note@-1 {{type declared here}}
// expected-error@-2 {{generic struct 'S' references itself}}
func f(a: A.T) {
g(a: id(t: a))
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
_ = A.T.self
}
func g(a: S<A>) {
f(a: id(t: a))
// expected-note@-1 {{expected an argument list of type '(a: A.T)'}}
// expected-error@-2 {{cannot invoke 'f' with an argument list of type '(a: S<A>)'}}
_ = S<A>.self
}
func id<T>(t: T) -> T {
return t
}
}
protocol I {
init()
}
protocol PI {
associatedtype T : I
}
struct SI<A: PI> : I where A : I, A.T == SI<A> {
// expected-note@-1 {{type declared here}}
// expected-error@-2 {{generic struct 'SI' references itself}}
func ggg<T : I>(t: T.Type) -> T {
return T()
}
func foo() {
_ = A()
_ = A.T()
_ = SI<A>()
_ = ggg(t: A.self)
_ = ggg(t: A.T.self)
_ = self.ggg(t: A.self)
_ = self.ggg(t: A.T.self)
}
}
// Used to hit infinite recursion
struct S4<A: PI> : I where A : I {
}
struct S5<A: PI> : I where A : I, A.T == S4<A> { }
// Used to hit ArchetypeBuilder assertions
struct SU<A: P> where A.T == SU {
}
struct SIU<A: PI> : I where A : I, A.T == SIU {
}
| 7e7f5799f0df7f66b9fd59869db6572c | 28.46729 | 140 | 0.641928 | false | false | false | false |
cuappdev/podcast-ios | refs/heads/master | EpisodeUtilityView.swift | mit | 1 | //
// EpisodeCellControlView.swift
// Recast
//
// Created by Jack Thompson on 10/21/18.
// Copyright © 2018 Cornell AppDev. All rights reserved.
//
import UIKit
class EpisodeUtilityView: UIView {
// MARK: - Variables
var playButton: UIButton!
var downloadButton: UIButton!
// TODO: later change to download status to indicate episode is downloading
var isDownloaded: Bool = false
init(frame: CGRect, isDownloaded: Bool) {
super.init(frame: frame)
playButton = UIButton()
playButton.setTitle("Play", for: .normal)
playButton.titleLabel?.font = .systemFont(ofSize: 14)
playButton.setTitleColor(.gray, for: .normal)
playButton.setImage(#imageLiteral(resourceName: "play_icon"), for: .normal)
downloadButton = UIButton()
downloadButton.titleLabel?.font = .systemFont(ofSize: 14)
downloadButton.setTitleColor(.gray, for: .normal)
downloadButton.setTitle(isDownloaded ? "Downloaded" : "Download", for: .normal)
downloadButton.setImage(isDownloaded ? #imageLiteral(resourceName: "downloaded_icon") : #imageLiteral(resourceName: "download_icon"), for: .normal)
addSubview(playButton)
addSubview(downloadButton)
setUpConstraints()
}
func setUpConstraints() {
// MARK: - Constants
let sidePadding = 18
let playButtonSize = CGSize(width: 16, height: 18)
let downloadButtonSize = CGSize(width: 16, height: 16)
playButton.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(sidePadding)
make.top.bottom.equalToSuperview()
}
playButton.imageView?.snp.makeConstraints { make in
make.size.equalTo(playButtonSize)
make.leading.centerY.equalToSuperview()
}
downloadButton.snp.makeConstraints { make in
make.trailing.equalToSuperview().inset(sidePadding)
make.top.bottom.equalToSuperview()
}
downloadButton.imageView?.snp.makeConstraints { make in
make.size.equalTo(downloadButtonSize)
make.leading.centerY.equalToSuperview()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| f314af33e36e111445b8d8dfe26ec66b | 30.561644 | 155 | 0.655382 | false | false | false | false |
br1sk/brisk-ios | refs/heads/master | Brisk iOS/App/AppDelegate.swift | mit | 1 | import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// MARK: - Properties
var window: UIWindow?
var appCoordinator: AppCoordinator?
// MARK: - UIApplicationDelegate Methods
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let coordinator = AppCoordinator()
window = coordinator.start()
appCoordinator = coordinator
return true
}
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
if let type = QuickAction.Radar(rawValue: shortcutItem.type) {
appCoordinator?.handleQuick(action: type)
completionHandler(true)
}
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool {
guard let coordinator = appCoordinator else { return false }
return coordinator.handle(url: url)
}
}
| 095f61cf790f70e05e82f183931ef579 | 31.40625 | 155 | 0.736741 | false | false | false | false |
yeziahehe/Gank | refs/heads/master | Gank/ViewControllers/Category/ArticleViewController.swift | gpl-3.0 | 1 | //
// ArticleViewController.swift
// Gank
//
// Created by 叶帆 on 2017/7/26.
// Copyright © 2017年 Suzhou Coryphaei Information&Technology Co., Ltd. All rights reserved.
//
import UIKit
class ArticleViewController: BaseViewController {
public var category: String!
fileprivate var gankArray = [Gank]()
fileprivate var page: Int = 1
fileprivate var canLoadMore: Bool = false
fileprivate var isLoading: Bool = false
fileprivate var isNoData: Bool = false
@IBOutlet weak var articleTableView: UITableView! {
didSet {
articleTableView.tableFooterView = UIView()
articleTableView.refreshControl = refreshControl
articleTableView.registerNibOf(DailyGankCell.self)
articleTableView.registerNibOf(ArticleGankLoadingCell.self)
articleTableView.registerNibOf(LoadMoreCell.self)
}
}
fileprivate var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl.init()
refreshControl.layer.zPosition = -1
refreshControl.addTarget(self, action: #selector(refresh(_:)), for: .valueChanged)
return refreshControl
}()
fileprivate lazy var noDataFooterView: NoDataFooterView = {
let noDataFooterView = NoDataFooterView.instanceFromNib()
noDataFooterView.reasonAction = { [weak self] in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let networkViewController = storyboard.instantiateViewController(withIdentifier: "NetworkViewController")
self?.navigationController?.pushViewController(networkViewController , animated: true)
}
noDataFooterView.reloadAction = { [weak self] in
self?.refreshControl.beginRefreshing()
self?.articleTableView.contentOffset = CGPoint(x:0, y: 0-(self?.refreshControl.frame.size.height)!)
self?.refresh((self?.refreshControl)!)
}
noDataFooterView.frame = CGRect(x: 0, y: 0, width: GankConfig.getScreenWidth(), height: GankConfig.getScreenHeight()-64)
return noDataFooterView
}()
fileprivate lazy var customFooterView: CustomFooterView = {
let footerView = CustomFooterView.instanceFromNib()
footerView.frame = CGRect(x: 0, y: 0, width: GankConfig.getScreenWidth(), height: 73)
return footerView
}()
deinit {
articleTableView?.delegate = nil
gankLog.debug("deinit ArticleViewController")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
refreshControl.endRefreshing()
}
override func viewDidLoad() {
super.viewDidLoad()
title = category
updateArticleView()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let identifier = segue.identifier else {
return
}
switch identifier {
case "showDetail":
let vc = segue.destination as! GankDetailViewController
let url = sender as! String
vc.gankURL = url
default:
break
}
}
fileprivate enum UpdateArticleViewMode {
case first
case top
case loadMore
}
fileprivate func updateArticleView(mode: UpdateArticleViewMode = .first, finish: (() -> Void)? = nil) {
if isLoading {
finish?()
return
}
isNoData = false
isLoading = true
var maxPage = page
switch mode {
case .first:
canLoadMore = true
maxPage = 1
articleTableView.isScrollEnabled = false
articleTableView.separatorStyle = .none
articleTableView.rowHeight = 94
//noDataFooterView.removeFromSuperview()
case .top:
maxPage = 1
canLoadMore = true
articleTableView.estimatedRowHeight = 195.5
articleTableView.rowHeight = UITableView.automaticDimension
case .loadMore:
maxPage += 1
}
let failureHandler: FailureHandler = { reason, message in
SafeDispatch.async { [weak self] in
switch mode {
case .first:
//self?.view.addSubview((self?.noDataFooterView)!)
self?.isNoData = true
self?.articleTableView.isScrollEnabled = true
self?.articleTableView.tableFooterView = self?.noDataFooterView
self?.articleTableView.reloadData()
gankLog.debug("加载失败")
case .top, .loadMore:
GankHUD.error("加载失败")
gankLog.debug("加载失败")
}
self?.isLoading = false
finish?()
}
}
gankofCategory(category: category, page: maxPage, failureHandler: failureHandler, completion: { (data) in
SafeDispatch.async { [weak self] in
self?.isNoData = false
self?.articleTableView.isScrollEnabled = true
self?.articleTableView.tableFooterView = UIView()
guard let strongSelf = self else {
return
}
strongSelf.canLoadMore = (data.count == 20)
strongSelf.page = maxPage
let newGankArray = data
let oldGankArray = strongSelf.gankArray
var wayToUpdate: UITableView.WayToUpdate = .none
switch mode {
case .first:
strongSelf.gankArray = newGankArray
wayToUpdate = .reloadData
case .top:
strongSelf.gankArray = newGankArray
if Set(oldGankArray.map({ $0.id })) == Set(newGankArray.map({ $0.id })) {
wayToUpdate = .none
} else {
wayToUpdate = .reloadData
}
case .loadMore:
let oldGankArratCount = oldGankArray.count
let oldGankArrayIdSet = Set<String>(oldGankArray.map({ $0.id }))
var realNewGankArray = [Gank]()
for gank in newGankArray {
if !oldGankArrayIdSet.contains(gank.id) {
realNewGankArray.append(gank)
}
}
strongSelf.gankArray += realNewGankArray
let newGankArrayCount = strongSelf.gankArray.count
let indexPaths = Array(oldGankArratCount..<newGankArrayCount).map({ IndexPath(row: $0, section: 0) })
if !indexPaths.isEmpty {
wayToUpdate = .reloadData
}
if !strongSelf.canLoadMore {
strongSelf.articleTableView.tableFooterView = strongSelf.customFooterView
}
}
wayToUpdate.performWithTableView(strongSelf.articleTableView)
strongSelf.isLoading = false
finish?()
}
})
}
}
extension ArticleViewController {
@objc fileprivate func refresh(_ sender: UIRefreshControl) {
if isNoData {
updateArticleView() {
SafeDispatch.async {
sender.endRefreshing()
}
}
} else {
updateArticleView(mode: .top) {
SafeDispatch.async {
sender.endRefreshing()
}
}
}
}
}
// MARK: - UITableViewDataSource, UITableViewDelegate
extension ArticleViewController: UITableViewDataSource, UITableViewDelegate {
fileprivate enum Section: Int {
case gank
case loadMore
}
func numberOfSections(in tableView: UITableView) -> Int {
guard isNoData else {
return gankArray.isEmpty || !canLoadMore ? 1 : 2
}
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard !isNoData else {
return 0
}
guard !gankArray.isEmpty else {
return 8
}
guard let section = Section(rawValue: section) else {
fatalError("Invalid Section")
}
switch section {
case .gank:
return gankArray.count
case .loadMore:
return canLoadMore ? 1 : 0
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard gankArray.isEmpty else {
guard let section = Section(rawValue: indexPath.section) else {
fatalError("Invalid Section")
}
switch section {
case .gank:
let cell: DailyGankCell = tableView.dequeueReusableCell()
let gankDetail: Gank = gankArray[indexPath.row]
if category == "all" {
cell.configure(withGankDetail: gankDetail, isHiddenTag: false)
} else {
cell.configure(withGankDetail: gankDetail)
}
cell.selectionStyle = UITableViewCell.SelectionStyle.default
return cell
case .loadMore:
let cell: LoadMoreCell = tableView.dequeueReusableCell()
cell.isLoading = true
return cell
}
}
let cell: ArticleGankLoadingCell = tableView.dequeueReusableCell()
cell.selectionStyle = UITableViewCell.SelectionStyle.none
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let section = Section(rawValue: indexPath.section) else {
fatalError("Invalid Section")
}
switch section {
case .gank:
break
case .loadMore:
guard let cell = cell as? LoadMoreCell else {
break
}
guard canLoadMore else {
cell.isLoading = false
break
}
gankLog.debug("load more gank")
if !cell.isLoading {
cell.isLoading = true
}
updateArticleView(mode: .loadMore, finish: { [weak cell] in
cell?.isLoading = false
})
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
defer {
tableView.deselectRow(at: indexPath, animated: true)
}
if !gankArray.isEmpty {
let gankDetail: Gank = gankArray[indexPath.row]
self.performSegue(withIdentifier: "showDetail", sender: gankDetail.url)
}
}
}
| 64d27737a297fafab19034b62d0b3eb3 | 31.497297 | 128 | 0.526613 | false | false | false | false |
skedgo/tripkit-ios | refs/heads/main | Sources/TripKitUI/view model/TKUITripOverviewViewModel+Fetch.swift | apache-2.0 | 1 | //
// TKUITripOverviewViewModel+Fetch.swift
// TripKitUI-iOS
//
// Created by Adrian Schönig on 07.03.19.
// Copyright © 2019 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import RxSwift
import TripKit
extension TKUITripOverviewViewModel {
static func fetchContentOfServices(in trip: Trip) -> Observable<Void> {
let queries: [(Service, Date, TKRegion)] = trip.segments
.filter { !$0.isContinuation } // the previous segment will provide that
.compactMap { $0.service != nil ? ($0.service!, $0.departureTime, $0.startRegion ?? .international) : nil }
.filter { $0.0.hasServiceData == false }
let requests: [Observable<Void>] = queries
.map(TKBuzzInfoProvider.rx.downloadContent)
.map { $0.asObservable() }
let merged = Observable<Void>.merge(requests)
return merged.throttle(.milliseconds(500), latest: true, scheduler: MainScheduler.asyncInstance)
}
}
| a85ffa110d032943e0f09c11ae2b3e5a | 28.28125 | 113 | 0.689434 | false | false | false | false |
fanyu/EDCCharla | refs/heads/master | EDCChat/EDCChat/EDCChatCardView.swift | mit | 1 | //
// EDCChatCardView.swift
// EDCChat
//
// Created by FanYu on 11/12/2015.
// Copyright © 2015 FanYu. All rights reserved.
//
import UIKit
class EDCChatCardView: UIView {
private(set) lazy var titleLabel = UILabel()
var user: EDCChatUserProtocol? {
willSet {
titleLabel.text = newValue?.name ?? newValue?.identifier ?? "<Unknow>"
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup() {
let vs = ["t" : titleLabel]
// title label
titleLabel.font = UIFont.systemFontOfSize(14)
titleLabel.textColor = UIColor.lightGrayColor()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
// add subview
addSubview(titleLabel)
// constraint
addConstraints(NSLayoutConstraintMake("H:|-(8)-[t]-(8)-|", views: vs))
addConstraints(NSLayoutConstraintMake("V:|-(0)-[t]-(0)-|", views: vs))
}
}
| 37b78707d7eeb6ac806a32b04552c6d7 | 24.022222 | 82 | 0.587922 | false | false | false | false |
SettlePad/client-iOS | refs/heads/master | SettlePad/Balances.swift | mit | 1 | //
// Balance.swift
// SettlePad
//
// Created by Rob Everhardt on 10/05/15.
// Copyright (c) 2015 SettlePad. All rights reserved.
//
import Foundation
import SwiftyJSON
class Balances {
private(set) var balances = [Balance]()
private(set) var currenciesSummary = [CurrencySummary]()
private(set) var sortedCurrencies = [Currency]()
init() {
}
func getBalancesForCurrency(currency: Currency)->[Balance] {
return balances.filter { $0.currency == currency}.sort({ (Balance1, Balance2) -> Bool in
return Balance1.balance > Balance2.balance
})
}
/*func getBalancesForContact(contact: Contact)->[Balance] {
return balances.filter { $0.contact == contact}
}*/
func getSummaryForCurrency(currency: Currency)->CurrencySummary? {
let returnArray = currenciesSummary.filter { $0.currency == currency}
return returnArray.first
}
func updateBalances(success: ()->(), failure: (error:SettlePadError)->()) {
HTTPWrapper.request("balance/currencies", method: .GET, authenticateWithUser: activeUser!,
success: {json in
self.balances = []
self.currenciesSummary = []
for (rawCurrency,connectionJSON):(String, JSON) in json["data"]["connections"] {
for (_,connection):(String, JSON) in connectionJSON {
if let
contactIdentifier = connection["primary_identifier"].string,
contactName = connection["name"].string,
contactIban = connection["iban"].string,
balance = connection["balance"].double,
unprocessed = connection["unprocessed"].bool,
currency = Currency(rawValue: rawCurrency)
{
self.balances.append(Balance(identifierStr: contactIdentifier, name: contactName, iban: contactIban, currency: currency, balance: balance, unprocessed: unprocessed))
}
}
}
for (rawCurrency,balance):(String, JSON) in json["data"]["summary"] {
if let
get = balance["get"].double,
owe = balance["owe"].double,
currency = Currency(rawValue: rawCurrency)
{
if get != 0 || owe != 0 {
self.currenciesSummary.append(CurrencySummary(currency: currency, get: get, owe: owe))
}
}
}
self.sortedCurrencies = []
for currencySummary in self.currenciesSummary {
self.sortedCurrencies.append(currencySummary.currency)
}
self.sortedCurrencies.sortInPlace({(left: Currency, right: Currency) -> Bool in
left.toLongName().localizedCaseInsensitiveCompare(right.toLongName()) == NSComparisonResult.OrderedDescending})
success()
},
failure: { error in
failure(error: error)
}
)
}
}
class CurrencySummary {
var currency: Currency
var get: Double
var owe: Double
var balance: Double
init (currency: Currency, get: Double, owe: Double) {
self.currency = currency
self.get = get
self.owe = owe
self.balance = get+owe
}
}
| d45a35cd52813379a33615a882babbef | 27.79798 | 172 | 0.673097 | false | false | false | false |
CodaFi/swift | refs/heads/main | benchmark/single-source/RangeReplaceableCollectionPlusDefault.swift | apache-2.0 | 22 | // RangeReplaceablePlusDefault benchmark
//
// Source: https://gist.github.com/airspeedswift/392599e7eeeb74b481a7
import TestsUtils
public var RangeReplaceableCollectionPlusDefault = BenchmarkInfo(
name: "RangeReplaceableCollectionPlusDefault",
runFunction: run_RangeReplaceableCollectionPlusDefault,
tags: [.validation],
legacyFactor: 4
)
@inline(never)
public func run_RangeReplaceableCollectionPlusDefault(_ N: Int) {
let stringsRef = [1, 2, 3]
let strings = ["1", "2", "3"]
let toInt = { (s: String) -> Int? in Int(s) }
var a = [Int]()
var b = [Int]()
for _ in 1...250*N {
let a2: Array = mapSome(strings, toInt)
let b2 = mapSome(strings, toInt)
a = a2
b = b2
if !compareRef(a, b, stringsRef) {
break
}
}
CheckResults(compareRef(a, b, stringsRef))
}
func compareRef(_ a: [Int], _ b: [Int], _ ref: [Int]) -> Bool {
return ref == a && ref == b
}
// This algorithm returns a generic placeholder
// that can be any kind of range-replaceable collection:
func mapSome
<S: Sequence, C: RangeReplaceableCollection>
(_ source: S, _ transform: (S.Element)->C.Element?) -> C {
var result = C()
for x in source {
if let y = transform(x) {
result.append(y)
}
}
return result
}
// If you write a second version that returns an array,
// you can call the more general version for implementation:
func mapSome<S: Sequence,U>(_ source: S, _ transform: (S.Element)->U?)->[U] {
// just calls the more generalized version
// (works because here, the return type
// is now of a specific type, an Array)
return mapSome(source, transform)
}
| 9567ce28149fff553d73012f726273d4 | 25.508197 | 77 | 0.666667 | false | false | false | false |
IngmarStein/swift | refs/heads/master | test/SILGen/protocol_resilience.swift | apache-2.0 | 7 | // RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-silgen -enable-resilience %s | %FileCheck %s --check-prefix=CHECK
import resilient_protocol
prefix operator ~~~ {}
infix operator <*> {}
infix operator <**> {}
infix operator <===> {}
public protocol P {}
// Protocol is public -- needs resilient witness table
public protocol ResilientMethods {
associatedtype AssocType : P
func defaultWitness()
func anotherDefaultWitness(_ x: Int) -> Self
func defaultWitnessWithAssociatedType(_ a: AssocType)
func defaultWitnessMoreAbstractThanRequirement(_ a: AssocType, b: Int)
func defaultWitnessMoreAbstractThanGenericRequirement<T>(_ a: AssocType, t: T)
func noDefaultWitness()
func defaultWitnessIsNotPublic()
static func staticDefaultWitness(_ x: Int) -> Self
}
extension ResilientMethods {
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientMethods14defaultWitnessfT_T_
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_16ResilientMethods14defaultWitnessfT_T_
public func defaultWitness() {}
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientMethods21anotherDefaultWitnessfSix
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_16ResilientMethods21anotherDefaultWitnessfSix
public func anotherDefaultWitness(_ x: Int) -> Self {}
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientMethods32defaultWitnessWithAssociatedTypefwx9AssocTypeT_
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_16ResilientMethods32defaultWitnessWithAssociatedTypefwx9AssocTypeT_
public func defaultWitnessWithAssociatedType(_ a: AssocType) {}
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientMethods41defaultWitnessMoreAbstractThanRequirementfTwx9AssocType1bSi_T_
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_16ResilientMethods41defaultWitnessMoreAbstractThanRequirementu0_rfTqd__1bqd_0__T_
public func defaultWitnessMoreAbstractThanRequirement<A, T>(_ a: A, b: T) {}
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientMethods48defaultWitnessMoreAbstractThanGenericRequirementurfTwx9AssocType1tqd___T_
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_16ResilientMethods48defaultWitnessMoreAbstractThanGenericRequirementu0_rfTqd__1tqd_0__T_
public func defaultWitnessMoreAbstractThanGenericRequirement<A, T>(_ a: A, t: T) {}
// CHECK-LABEL: sil [transparent] [thunk] @_TZFP19protocol_resilience16ResilientMethods20staticDefaultWitnessfSix
// CHECK-LABEL: sil @_TZFE19protocol_resiliencePS_16ResilientMethods20staticDefaultWitnessfSix
public static func staticDefaultWitness(_ x: Int) -> Self {}
// CHECK-LABEL: sil private @_TFE19protocol_resiliencePS_16ResilientMethodsP{{.*}}25defaultWitnessIsNotPublicfT_T_
private func defaultWitnessIsNotPublic() {}
}
public protocol ResilientConstructors {
init(noDefault: ())
init(default: ())
init?(defaultIsOptional: ())
init?(defaultNotOptional: ())
init(optionalityMismatch: ())
}
extension ResilientConstructors {
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience21ResilientConstructorsCfT7defaultT__x
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_21ResilientConstructorsCfT7defaultT__x
public init(default: ()) {
self.init(noDefault: ())
}
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience21ResilientConstructorsCfT17defaultIsOptionalT__GSqx_
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_21ResilientConstructorsCfT17defaultIsOptionalT__GSqx_
public init?(defaultIsOptional: ()) {
self.init(noDefault: ())
}
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_21ResilientConstructorsCfT20defaultIsNotOptionalT__x
public init(defaultIsNotOptional: ()) {
self.init(noDefault: ())
}
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_21ResilientConstructorsCfT19optionalityMismatchT__GSqx_
public init?(optionalityMismatch: ()) {
self.init(noDefault: ())
}
}
public protocol ResilientStorage {
associatedtype T : ResilientConstructors
var propertyWithDefault: Int { get }
var propertyWithNoDefault: Int { get }
var mutablePropertyWithDefault: Int { get set }
var mutablePropertyNoDefault: Int { get set }
var mutableGenericPropertyWithDefault: T { get set }
subscript(x: T) -> T { get set }
var mutatingGetterWithNonMutatingDefault: Int { mutating get set }
}
extension ResilientStorage {
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientStorageg19propertyWithDefaultSi
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_16ResilientStorageg19propertyWithDefaultSi
public var propertyWithDefault: Int {
get { return 0 }
}
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientStorageg26mutablePropertyWithDefaultSi
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_16ResilientStorageg26mutablePropertyWithDefaultSi
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientStorages26mutablePropertyWithDefaultSi
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_16ResilientStorages26mutablePropertyWithDefaultSi
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientStoragem26mutablePropertyWithDefaultSi
// CHECK-LABEL: sil [transparent] @_TFFP19protocol_resilience16ResilientStoragem26mutablePropertyWithDefaultSiU_T_
public var mutablePropertyWithDefault: Int {
get { return 0 }
set { }
}
public private(set) var mutablePropertyNoDefault: Int {
get { return 0 }
set { }
}
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientStorageg33mutableGenericPropertyWithDefaultwx1T
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_16ResilientStorageg33mutableGenericPropertyWithDefaultwx1T
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientStorages33mutableGenericPropertyWithDefaultwx1T
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_16ResilientStorages33mutableGenericPropertyWithDefaultwx1T
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientStoragem33mutableGenericPropertyWithDefaultwx1T
// CHECK-LABEL: sil [transparent] @_TFFP19protocol_resilience16ResilientStoragem33mutableGenericPropertyWithDefaultwx1TU_T_
public var mutableGenericPropertyWithDefault: T {
get {
return T(default: ())
}
set { }
}
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientStorageg9subscriptFwx1TwxS1_
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_16ResilientStorageg9subscriptFwx1TwxS1_
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientStorages9subscriptFwx1TwxS1_
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_16ResilientStorages9subscriptFwx1TwxS1_
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientStoragem9subscriptFwx1TwxS1_
// CHECK-LABEL: sil [transparent] @_TFFP19protocol_resilience16ResilientStoragem9subscriptFwx1TwxS1_U_T_
public subscript(x: T) -> T {
get {
return x
}
set { }
}
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientStorageg36mutatingGetterWithNonMutatingDefaultSi
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_16ResilientStorageg36mutatingGetterWithNonMutatingDefaultSi
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientStorages36mutatingGetterWithNonMutatingDefaultSi
// CHECK-LABEL: sil @_TFE19protocol_resiliencePS_16ResilientStorages36mutatingGetterWithNonMutatingDefaultSi
// CHECK-LABEL: sil [transparent] [thunk] @_TFP19protocol_resilience16ResilientStoragem36mutatingGetterWithNonMutatingDefaultSi
// CHECK-LABEL: sil [transparent] @_TFFP19protocol_resilience16ResilientStoragem36mutatingGetterWithNonMutatingDefaultSiU_T_
public var mutatingGetterWithNonMutatingDefault: Int {
get {
return 0
}
set { }
}
}
public protocol ResilientOperators {
associatedtype AssocType : P
static prefix func ~~~(s: Self)
static func <*><T>(s: Self, t: T)
static func <**><T>(t: T, s: Self) -> AssocType
static func <===><T : ResilientOperators>(t: T, s: Self) -> T.AssocType
}
// CHECK-LABEL: sil [transparent] [thunk] @_TZFP19protocol_resilience18ResilientOperatorsop3tttfxT_
// CHECK-LABEL: sil @_TF19protocol_resilienceop3ttturFxT_
public prefix func ~~~<S>(s: S) {}
// CHECK-LABEL: sil [transparent] [thunk] @_TZFP19protocol_resilience18ResilientOperatorsoi3lmgurfTxqd___T_
// CHECK-LABEL: sil @_TF19protocol_resilienceoi3lmgu0_rFTq_x_T_
public func <*><T, S>(s: S, t: T) {}
// Swap the generic parameters to make sure we don't mix up our DeclContexts
// when mapping interface types in and out
// CHECK-LABEL: sil [transparent] [thunk] @_TZFP19protocol_resilience18ResilientOperatorsoi4lmmgurfTqd__x_wx9AssocType
// CHECK-LABEL: sil @_TF19protocol_resilienceoi4lmmgu0_RxS_18ResilientOperatorsrFTq_x_wx9AssocType
public func <**><S : ResilientOperators, T>(t: T, s: S) -> S.AssocType {}
// CHECK-LABEL: sil [transparent] [thunk] @_TZFP19protocol_resilience18ResilientOperatorsoi5leeeguRd__S0_rfTqd__x_wd__9AssocType
// CHECK-LABEL: sil @_TF19protocol_resilienceoi5leeegu0_RxS_18ResilientOperators_S0_rFTxq__wx9AssocType
public func <===><T : ResilientOperators, S : ResilientOperators>(t: T, s: S) -> T.AssocType {}
public protocol ReabstractSelfBase {
// No requirements
}
public protocol ReabstractSelfRefined : class, ReabstractSelfBase {
// A requirement with 'Self' abstracted as a class instance
var callback: (Self) -> Self { get set }
}
func id<T>(_ t: T) -> T {}
extension ReabstractSelfBase {
// A witness for the above requirement, but with 'Self' maximally abstracted
public var callback: (Self) -> Self {
get { return id }
nonmutating set { }
}
}
final class X : ReabstractSelfRefined {}
func inoutFunc(_ x: inout Int) {}
// CHECK-LABEL: sil hidden @_TF19protocol_resilience22inoutResilientProtocolFRP18resilient_protocol22OtherResilientProtocol_T_
func inoutResilientProtocol(_ x: inout OtherResilientProtocol) {
// CHECK: function_ref @_TFE18resilient_protocolPS_22OtherResilientProtocolm19propertyInExtensionSi
inoutFunc(&x.propertyInExtension)
}
struct OtherConformingType : OtherResilientProtocol {}
// CHECK-LABEL: sil hidden @_TF19protocol_resilience22inoutResilientProtocolFRVS_19OtherConformingTypeT_
func inoutResilientProtocol(_ x: inout OtherConformingType) {
// CHECK: function_ref @_TFE18resilient_protocolPS_22OtherResilientProtocolm19propertyInExtensionSi
inoutFunc(&x.propertyInExtension)
// CHECK: function_ref @_TZFE18resilient_protocolPS_22OtherResilientProtocolm25staticPropertyInExtensionSi
inoutFunc(&OtherConformingType.staticPropertyInExtension)
}
// Protocol is not public -- make sure default witnesses have the right linkage
protocol InternalProtocol {
func noDefaultF()
func defaultG()
}
extension InternalProtocol {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TFP19protocol_resilience16InternalProtocol8defaultGfT_T_
// CHECK: return
func defaultG() {}
}
// CHECK-LABEL: sil_default_witness_table P {
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ResilientMethods {
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientMethods.defaultWitness!1: @_TFP19protocol_resilience16ResilientMethods14defaultWitnessfT_T_
// CHECK-NEXT: method #ResilientMethods.anotherDefaultWitness!1: @_TFP19protocol_resilience16ResilientMethods21anotherDefaultWitnessfSix
// CHECK-NEXT: method #ResilientMethods.defaultWitnessWithAssociatedType!1: @_TFP19protocol_resilience16ResilientMethods32defaultWitnessWithAssociatedTypefwx9AssocTypeT_
// CHECK-NEXT: method #ResilientMethods.defaultWitnessMoreAbstractThanRequirement!1: @_TFP19protocol_resilience16ResilientMethods41defaultWitnessMoreAbstractThanRequirementfTwx9AssocType1bSi_T_
// CHECK-NEXT: method #ResilientMethods.defaultWitnessMoreAbstractThanGenericRequirement!1: @_TFP19protocol_resilience16ResilientMethods48defaultWitnessMoreAbstractThanGenericRequirementurfTwx9AssocType1tqd___T_
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientMethods.staticDefaultWitness!1: @_TZFP19protocol_resilience16ResilientMethods20staticDefaultWitnessfSix
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ResilientConstructors {
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientConstructors.init!allocator.1: @_TFP19protocol_resilience21ResilientConstructorsCfT7defaultT__x
// CHECK-NEXT: method #ResilientConstructors.init!allocator.1: @_TFP19protocol_resilience21ResilientConstructorsCfT17defaultIsOptionalT__GSqx_
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ResilientStorage {
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientStorage.propertyWithDefault!getter.1: @_TFP19protocol_resilience16ResilientStorageg19propertyWithDefaultSi
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientStorage.mutablePropertyWithDefault!getter.1: @_TFP19protocol_resilience16ResilientStorageg26mutablePropertyWithDefaultSi
// CHECK-NEXT: method #ResilientStorage.mutablePropertyWithDefault!setter.1: @_TFP19protocol_resilience16ResilientStorages26mutablePropertyWithDefaultSi
// CHECK-NEXT: method #ResilientStorage.mutablePropertyWithDefault!materializeForSet.1: @_TFP19protocol_resilience16ResilientStoragem26mutablePropertyWithDefaultSi
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientStorage.mutableGenericPropertyWithDefault!getter.1: @_TFP19protocol_resilience16ResilientStorageg33mutableGenericPropertyWithDefaultwx1T
// CHECK-NEXT: method #ResilientStorage.mutableGenericPropertyWithDefault!setter.1: @_TFP19protocol_resilience16ResilientStorages33mutableGenericPropertyWithDefaultwx1T
// CHECK-NEXT: method #ResilientStorage.mutableGenericPropertyWithDefault!materializeForSet.1: @_TFP19protocol_resilience16ResilientStoragem33mutableGenericPropertyWithDefaultwx1T
// CHECK-NEXT: method #ResilientStorage.subscript!getter.1: @_TFP19protocol_resilience16ResilientStorageg9subscriptFwx1TwxS1_
// CHECK-NEXT: method #ResilientStorage.subscript!setter.1: @_TFP19protocol_resilience16ResilientStorages9subscriptFwx1TwxS1_
// CHECK-NEXT: method #ResilientStorage.subscript!materializeForSet.1: @_TFP19protocol_resilience16ResilientStoragem9subscriptFwx1TwxS1_
// CHECK-NEXT: method #ResilientStorage.mutatingGetterWithNonMutatingDefault!getter.1: @_TFP19protocol_resilience16ResilientStorageg36mutatingGetterWithNonMutatingDefaultSi
// CHECK-NEXT: method #ResilientStorage.mutatingGetterWithNonMutatingDefault!setter.1: @_TFP19protocol_resilience16ResilientStorages36mutatingGetterWithNonMutatingDefaultSi
// CHECK-NEXT: method #ResilientStorage.mutatingGetterWithNonMutatingDefault!materializeForSet.1: @_TFP19protocol_resilience16ResilientStoragem36mutatingGetterWithNonMutatingDefaultSi
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ResilientOperators {
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientOperators."~~~"!1: @_TZFP19protocol_resilience18ResilientOperatorsop3tttfxT_
// CHECK-NEXT: method #ResilientOperators."<*>"!1: @_TZFP19protocol_resilience18ResilientOperatorsoi3lmgurfTxqd___T_
// CHECK-NEXT: method #ResilientOperators."<**>"!1: @_TZFP19protocol_resilience18ResilientOperatorsoi4lmmgurfTqd__x_wx9AssocType
// CHECK-NEXT: method #ResilientOperators."<===>"!1: @_TZFP19protocol_resilience18ResilientOperatorsoi5leeeguRd__S0_rfTqd__x_wd__9AssocType
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ReabstractSelfRefined {
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ReabstractSelfRefined.callback!getter.1: @_TFP19protocol_resilience21ReabstractSelfRefinedg8callbackFxx
// CHECK-NEXT: method #ReabstractSelfRefined.callback!setter.1: @_TFP19protocol_resilience21ReabstractSelfRefineds8callbackFxx
// CHECK-NEXT: method #ReabstractSelfRefined.callback!materializeForSet.1: @_TFP19protocol_resilience21ReabstractSelfRefinedm8callbackFxx
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table hidden InternalProtocol {
// CHECK-NEXT: no_default
// CHECK-NEXT: method #InternalProtocol.defaultG!1: @_TFP19protocol_resilience16InternalProtocol8defaultGfT_T_
// CHECK-NEXT: }
| 8c56916afb77a812ce5edeeaad3780de | 50.277259 | 214 | 0.799878 | false | false | false | false |
pikacode/EBBannerView | refs/heads/master | EBBannerView/SwiftClasses/EBMuteDetector.swift | mit | 1 | //
// EBMuteDetector.swift
// EBBannerViewSwift
//
// Created by pikacode on 2019/12/31.
//
import UIKit
import AudioToolbox
class EBMuteDetector: NSObject {
static let shared: EBMuteDetector = {
let url = Bundle(for: EBMuteDetector.self).url(forResource: "EBMuteDetector", withExtension: "mp3")! as CFURL
var detector = EBMuteDetector()
let status = AudioServicesCreateSystemSoundID(url, &detector.soundID)
if status == kAudioServicesNoError {
AudioServicesAddSystemSoundCompletion(detector.soundID, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue, completionProc, Unmanaged.passUnretained(detector).toOpaque())
var yes = 1
AudioServicesSetProperty(kAudioServicesPropertyIsUISound, UInt32(MemoryLayout<SystemSoundID>.size), &detector.soundID, UInt32(MemoryLayout<Bool>.size), &yes)
} else {
detector.soundID = .max
}
return detector
}()
static let completionProc: AudioServicesSystemSoundCompletionProc = {(soundID: SystemSoundID, p: UnsafeMutableRawPointer?) in
let elapsed = Date.timeIntervalSinceReferenceDate - shared.interval
let isMute = elapsed < 0.1
shared.completion(isMute)
}
var completion = { (mute: Bool) in }
var soundID: SystemSoundID = 1312
var interval: TimeInterval = 1
func detect(block: @escaping (Bool) -> ()) {
interval = NSDate.timeIntervalSinceReferenceDate
AudioServicesPlaySystemSound(soundID)
completion = block
}
deinit {
if (soundID != .max) {
AudioServicesRemoveSystemSoundCompletion(soundID);
AudioServicesDisposeSystemSoundID(soundID);
}
}
}
| 573e611cec525efe935e064670a634b4 | 32.113208 | 186 | 0.672365 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/NameBinding/import-specific-fixits.swift | apache-2.0 | 13 | // RUN: rm -f %t.*
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/ambiguous_left.swift
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/ambiguous_right.swift
// RUN: %target-swift-frontend -emit-module -o %t -I %t %S/Inputs/ambiguous.swift
// RUN: echo "public var x = Int()" | %target-swift-frontend -module-name FooBar -emit-module -o %t -
// RUN: %target-swift-frontend -typecheck -I %t -serialize-diagnostics-path %t.dia %s -verify
// RUN: c-index-test -read-diagnostics %t.dia > %t.deserialized_diagnostics.txt 2>&1
// RUN: %FileCheck --input-file=%t.deserialized_diagnostics.txt %s
import typealias Swift.Int
import struct Swift.Int
import class Swift.Int // expected-error {{'Int' was imported as 'class', but is a struct}} {{8-13=struct}}
import func Swift.Int // expected-error {{'Int' was imported as 'func', but is a struct}} {{8-12=struct}}
import var Swift.Int // expected-error {{'Int' was imported as 'var', but is a struct}} {{8-11=struct}}
// CHECK: [[@LINE-4]]:14: error: 'Int' was imported as 'class', but is a struct
// CHECK-NEXT: Number FIXITs = 1
// CHECK-NEXT: FIXIT: ([[FILE:.*import-specific-fixits.swift]]:[[@LINE-6]]:8 - [[FILE]]:[[@LINE-6]]:13): "struct"
// CHECK-NEXT: note: 'Int' declared here
import typealias Swift.IteratorProtocol // expected-error {{'IteratorProtocol' was imported as 'typealias', but is a protocol}} {{8-17=protocol}}
import struct Swift.IteratorProtocol // expected-error {{'IteratorProtocol' was imported as 'struct', but is a protocol}} {{8-14=protocol}}
import func Swift.IteratorProtocol // expected-error {{'IteratorProtocol' was imported as 'func', but is a protocol}} {{8-12=protocol}}
import class Swift.Int64 // expected-error {{'Int64' was imported as 'class', but is a struct}} {{8-13=struct}}
import class Swift.Bool // expected-error {{'Bool' was imported as 'class', but is a struct}} {{8-13=struct}}
import struct FooBar.x // expected-error {{'x' was imported as 'struct', but is a variable}} {{8-14=var}}
import struct Swift.print // expected-error {{'print' was imported as 'struct', but is a function}} {{8-14=func}}
// CHECK: [[@LINE-2]]:15: error: 'print' was imported as 'struct', but is a function
// CHECK-NEXT: Number FIXITs = 1
// CHECK-NEXT: FIXIT: ([[FILE]]:[[@LINE-4]]:8 - [[FILE]]:[[@LINE-4]]:14): "func"
// CHECK-NOT: note: 'print' declared here
import func ambiguous.funcOrVar // expected-error{{ambiguous name 'funcOrVar' in module 'ambiguous'}}
import var ambiguous.funcOrVar // expected-error{{ambiguous name 'funcOrVar' in module 'ambiguous'}}
import struct ambiguous.funcOrVar // expected-error{{ambiguous name 'funcOrVar' in module 'ambiguous'}}
// CHECK: [[@LINE-4]]:13: error: ambiguous name 'funcOrVar' in module 'ambiguous'
// CHECK-NEXT: Number FIXITs = 0
// CHECK-NEXT: note: found this candidate
// CHECK-NEXT: Number FIXITs = 0
// CHECK-NEXT: note: found this candidate
import func ambiguous.someVar // expected-error{{ambiguous name 'someVar' in module 'ambiguous'}}
import var ambiguous.someVar // expected-error{{ambiguous name 'someVar' in module 'ambiguous'}}
import struct ambiguous.someVar // expected-error{{ambiguous name 'someVar' in module 'ambiguous'}}
import struct ambiguous.SomeStruct // expected-error{{ambiguous name 'SomeStruct' in module 'ambiguous'}}
import typealias ambiguous.SomeStruct // expected-error{{ambiguous name 'SomeStruct' in module 'ambiguous'}}
import class ambiguous.SomeStruct // expected-error{{ambiguous name 'SomeStruct' in module 'ambiguous'}}
import func ambiguous.overloadedFunc // no-warning
| 2d8908ba221778595a942b670c3c5c4b | 59.066667 | 145 | 0.713097 | false | false | false | false |
STShenZhaoliang/STWeiBo | refs/heads/master | STWeiBo/STWeiBo/Classes/Compose/EmoticonKeyboard/EmoticonAttachment.swift | mit | 1 | //
// EmoticonAttachment.swift
// STWeiBo
//
// Created by ST on 15/11/24.
// Copyright © 2015年 ST. All rights reserved.
//
import UIKit
class EmoticonAttachment: NSTextAttachment {
/// 表情文字
var chs: String?
/// 使用表情模型,生成一个`属性字符串`
class func emoticonString(emoticon: Emoticon, font: UIFont) -> NSAttributedString {
let attachment = EmoticonAttachment()
// 记录表情符号的文本
attachment.chs = emoticon.chs
attachment.image = UIImage(named: emoticon.imagePath!)
// 设置表情大小
let s = font.lineHeight
attachment.bounds = CGRect(x: 0, y: -4, width: s, height: s)
// 2.根据附件创建属性文本
let imageText = NSAttributedString(attachment: attachment)
// 3.获得现在的属性文本
let strM = NSMutableAttributedString(attributedString: imageText)
// 4.设置表情图片的字体
strM.addAttribute(NSFontAttributeName, value:font, range: NSMakeRange(0, 1))
return strM
}
}
| 70d7f05efd8e061ad2130c2494093295 | 26.472222 | 87 | 0.617796 | false | false | false | false |
zerovagner/Desafio-Mobfiq | refs/heads/master | desafioMobfiq/desafioMobfiq/Remote.swift | mit | 1 | //
// Remote.swift
// desafioMobfiq
//
// Created by Vagner Oliveira on 6/16/17.
// Copyright © 2017 Vagner Oliveira. All rights reserved.
//
import Foundation
import Alamofire
func fetchItems (matchingQuery query: String = "", withOffset offset: Int = 0, andSize size: Int = 10, andApiQuery apiQuery: String = "", completed: @escaping (_ list: [Product]?) -> ()) {
let addr = URL(string: "https://desafio.mobfiq.com.br/Search/Criteria")!
let params = [
"query" : query,
"offset": offset,
"size": size,
"apiquery" : apiQuery
] as [String : Any]
var productList: [Product] = []
Alamofire.request(addr, method: .post, parameters: params).validate().responseJSON {
response in
switch response.result {
case .success(let value):
if let content = value as? [String:Any] {
if let list = content["Products"] as? [[String:Any]] {
productList = Product.generateProductList(fromData: list)
completed(productList)
}
}
case .failure(let error):
print(error)
completed(nil)
}
}
}
func fetchCategories (completed: @escaping (_ list: [Category]?) -> ()) {
let addr = URL(string: "https://desafio.mobfiq.com.br/StorePreference/CategoryTree")!
var categoryList: [Category] = []
Alamofire.request(addr, method: .get, parameters: nil).validate().responseJSON {
response in
switch response.result {
case .success(let value):
if let content = value as? [String:Any] {
if let list = content["Categories"] as? [[String:Any]] {
categoryList = Category.generateCategoriesTree(fromData: list)
completed(categoryList)
}
}
case .failure(let error):
print(error)
completed(nil)
}
}
}
| 04b2b0daf1e04fb2a79669a0c7db7387 | 28.086207 | 189 | 0.659751 | false | false | false | false |
noppoMan/aws-sdk-swift | refs/heads/main | Sources/Soto/Services/Batch/Batch_Paginator.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension Batch {
/// Describes one or more of your compute environments. If you are using an unmanaged compute environment, you can use the DescribeComputeEnvironment operation to determine the ecsClusterArn that you should launch your Amazon ECS container instances into.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func describeComputeEnvironmentsPaginator<Result>(
_ input: DescribeComputeEnvironmentsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, DescribeComputeEnvironmentsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: describeComputeEnvironments,
tokenKey: \DescribeComputeEnvironmentsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func describeComputeEnvironmentsPaginator(
_ input: DescribeComputeEnvironmentsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (DescribeComputeEnvironmentsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: describeComputeEnvironments,
tokenKey: \DescribeComputeEnvironmentsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Describes a list of job definitions. You can specify a status (such as ACTIVE) to only return job definitions that match that status.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func describeJobDefinitionsPaginator<Result>(
_ input: DescribeJobDefinitionsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, DescribeJobDefinitionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: describeJobDefinitions,
tokenKey: \DescribeJobDefinitionsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func describeJobDefinitionsPaginator(
_ input: DescribeJobDefinitionsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (DescribeJobDefinitionsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: describeJobDefinitions,
tokenKey: \DescribeJobDefinitionsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Describes one or more of your job queues.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func describeJobQueuesPaginator<Result>(
_ input: DescribeJobQueuesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, DescribeJobQueuesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: describeJobQueues,
tokenKey: \DescribeJobQueuesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func describeJobQueuesPaginator(
_ input: DescribeJobQueuesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (DescribeJobQueuesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: describeJobQueues,
tokenKey: \DescribeJobQueuesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of AWS Batch jobs. You must specify only one of the following: a job queue ID to return a list of jobs in that job queue a multi-node parallel job ID to return a list of that job's nodes an array job ID to return a list of that job's children You can filter the results by job status with the jobStatus parameter. If you do not specify a status, only RUNNING jobs are returned.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listJobsPaginator<Result>(
_ input: ListJobsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListJobsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listJobs,
tokenKey: \ListJobsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listJobsPaginator(
_ input: ListJobsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListJobsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listJobs,
tokenKey: \ListJobsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension Batch.DescribeComputeEnvironmentsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Batch.DescribeComputeEnvironmentsRequest {
return .init(
computeEnvironments: self.computeEnvironments,
maxResults: self.maxResults,
nextToken: token
)
}
}
extension Batch.DescribeJobDefinitionsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Batch.DescribeJobDefinitionsRequest {
return .init(
jobDefinitionName: self.jobDefinitionName,
jobDefinitions: self.jobDefinitions,
maxResults: self.maxResults,
nextToken: token,
status: self.status
)
}
}
extension Batch.DescribeJobQueuesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Batch.DescribeJobQueuesRequest {
return .init(
jobQueues: self.jobQueues,
maxResults: self.maxResults,
nextToken: token
)
}
}
extension Batch.ListJobsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Batch.ListJobsRequest {
return .init(
arrayJobId: self.arrayJobId,
jobQueue: self.jobQueue,
jobStatus: self.jobStatus,
maxResults: self.maxResults,
multiNodeJobId: self.multiNodeJobId,
nextToken: token
)
}
}
| f8fdb4952b1446d6b37574ccee287a3c | 43.7 | 409 | 0.64877 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/SILGen/pgo_checked_cast.swift | apache-2.0 | 3 | // RUN: rm -rf %t && mkdir %t
// RUN: %target-build-swift %s -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_checked_cast -o %t/main
// RUN: env LLVM_PROFILE_FILE=%t/default.profraw %target-run %t/main
// RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata
// RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-sorted-sil -emit-sil -module-name pgo_checked_cast -o - | %FileCheck %s --check-prefix=SIL
// need to lower checked_cast_addr_br(addr) into IR for this
// %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-ir -module-name pgo_checked_cast -o - | %FileCheck %s --check-prefix=IR
// RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-sorted-sil -emit-sil -module-name pgo_checked_cast -o - | %FileCheck %s --check-prefix=SIL-OPT
// need to lower checked_cast_addr_br(addr) into IR for this
// %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-ir -module-name pgo_checked_cast -o - | %FileCheck %s --check-prefix=IR-OPT
// REQUIRES: profile_runtime
// REQUIRES: OS=macosx
// SIL-LABEL: // pgo_checked_cast.check1<A>(Any, A) -> A
// SIL-LABEL: sil @_T016pgo_checked_cast6check1xyp_xtlF : $@convention(thin) <T> (@in Any, @in T) -> @out T !function_entry_count(5001) {
// IR-LABEL: define swiftcc i32 @_T06pgo_checked_cast6guess1s5Int32VAD1x_tF
// IR-OPT-LABEL: define swiftcc i32 @_T06pgo_checked_cast6guess1s5Int32VAD1x_tF
public func check1<T>(_ a : Any, _ t : T) -> T {
// SIL: checked_cast_addr_br take_always Any in {{.*}} : $*Any to T in {{.*}} : $*T, {{.*}}, {{.*}} !true_count(5000) !false_count(1)
// SIL-OPT: checked_cast_addr_br take_always Any in {{.*}} : $*Any to T in {{.*}} : $*T, {{.*}}, {{.*}} !true_count(5000) !false_count(1)
if let x = a as? T {
return x
} else {
return t
}
}
public class B {}
public class C : B {}
public class D : C {}
// SIL-LABEL: // pgo_checked_cast.check2(pgo_checked_cast.B) -> Swift.Int32
// SIL-LABEL: sil @_T016pgo_checked_cast6check2s5Int32VAA1BCF : $@convention(thin) (@owned B) -> Int32 !function_entry_count(5003) {
// IR-LABEL: define swiftcc i32 @_T06pgo_checked_cast6guess1s5Int32VAD1x_tF
// IR-OPT-LABEL: define swiftcc i32 @_T06pgo_checked_cast6guess1s5Int32VAD1x_tF
public func check2(_ a : B) -> Int32 {
// SIL: checked_cast_br %0 : $B to $D, {{.*}}, {{.*}} !true_count(5000)
// SIL: checked_cast_br %0 : $B to $C, {{.*}}, {{.*}} !true_count(2)
// SIL-OPT: checked_cast_br %0 : $B to $D, {{.*}}, {{.*}} !true_count(5000)
// SIL-OPT: checked_cast_br %0 : $B to $C, {{.*}}, {{.*}} !true_count(2)
switch a {
case is D:
return 42
case is C:
return 23
default:
return 13
}
}
func main() {
let answer : Int32 = 42
var sum : Int32 = 0
sum += check1("The answer to the life, the universe, and everything", answer)
sum += check2(B())
sum += check2(C())
sum += check2(C())
for i : Int32 in 1...5000 {
sum += check1(i, answer)
sum += check2(D())
}
}
main()
// IR: !{!"branch_weights", i32 5001, i32 2}
// IR-OPT: !{!"branch_weights", i32 5001, i32 2}
| b0e2677aa4da536906fd86035dd63c8c | 44.450704 | 196 | 0.638674 | false | false | false | false |
wikimedia/apps-ios-wikipedia | refs/heads/twn | Wikipedia/Code/Advanced Settings/InsertMediaImagePositionSettingsViewController.swift | mit | 1 | final class InsertMediaImagePositionSettingsViewController: ViewController {
private let tableView = UITableView()
private var selectedIndexPath: IndexPath?
typealias ImagePosition = InsertMediaSettings.Advanced.ImagePosition
func selectedImagePosition(isTextWrappingEnabled: Bool) -> ImagePosition {
guard isTextWrappingEnabled else {
return .none
}
guard let selectedIndexPath = selectedIndexPath else {
return .right
}
return viewModels[selectedIndexPath.row].imagePosition
}
struct ViewModel {
let imagePosition: ImagePosition
let title: String
let isSelected: Bool
init(imagePosition: ImagePosition, isSelected: Bool = false) {
self.imagePosition = imagePosition
self.title = imagePosition.displayTitle
self.isSelected = isSelected
}
}
private lazy var viewModels: [ViewModel] = {
let rightViewModel = ViewModel(imagePosition: .right, isSelected: true)
let leftViewModel = ViewModel(imagePosition: .left)
let centerViewModel = ViewModel(imagePosition: .center)
return [rightViewModel, leftViewModel, centerViewModel]
}()
override func viewDidLoad() {
scrollView = tableView
super.viewDidLoad()
navigationBar.isBarHidingEnabled = false
tableView.dataSource = self
tableView.delegate = self
view.wmf_addSubviewWithConstraintsToEdges(tableView)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: UITableViewCell.identifier)
tableView.separatorInset = .zero
tableView.tableFooterView = UIView()
title = ImagePosition.displayTitle
apply(theme: theme)
}
private func apply(theme: Theme, to cell: UITableViewCell) {
cell.backgroundColor = theme.colors.paperBackground
cell.contentView.backgroundColor = theme.colors.paperBackground
cell.textLabel?.textColor = theme.colors.primaryText
let selectedBackgroundView = UIView()
selectedBackgroundView.backgroundColor = theme.colors.midBackground
cell.selectedBackgroundView = selectedBackgroundView
}
// MARK: - Themeable
override func apply(theme: Theme) {
super.apply(theme: theme)
view.backgroundColor = theme.colors.paperBackground
tableView.backgroundColor = view.backgroundColor
tableView.separatorColor = theme.colors.border
}
}
extension InsertMediaImagePositionSettingsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.identifier, for: indexPath)
let viewModel = viewModels[indexPath.row]
cell.textLabel?.text = viewModel.title
cell.accessoryType = viewModel.isSelected ? .checkmark : .none
if viewModel.isSelected {
cell.accessoryType = .checkmark
selectedIndexPath = indexPath
} else {
cell.accessoryType = .none
}
apply(theme: theme, to: cell)
return cell
}
}
extension InsertMediaImagePositionSettingsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
guard
let selectedIndexPath = selectedIndexPath,
let selectedCell = tableView.cellForRow(at: selectedIndexPath)
else {
return indexPath
}
selectedCell.accessoryType = .none
return indexPath
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath)
selectedCell?.accessoryType = .checkmark
selectedIndexPath = indexPath
}
}
| 415b16e8da1b659ae70ecf2e66f32046 | 36.27027 | 108 | 0.685763 | false | false | false | false |
banxi1988/BXAppKit | refs/heads/master | BXForm/View/CodeEditorView.swift | mit | 1 | //
// CodeEditorView.swift
// BXAppKit
//
// Created by Haizhen Lee on 23/05/2017.
// Copyright © 2017 banxi1988. All rights reserved.
//
import Foundation
public class CodeView:UILabel{
public var size:CGSize = CGSize(width: 30, height: 30)
public override var intrinsicContentSize: CGSize{
return size
}
}
import UIKit
import BXModel
import BXiOSUtils
open class CodeEditorView : UIView,UITextFieldDelegate{
public let hiddenTextField = UITextField(frame:CGRect.zero)
public let stackView = UIStackView(frame: .zero)
public let codeCount:Int
public let codeViews:[CodeView]
public var codeViewSize:CGSize = CGSize(width: 40, height: 40){
didSet{
for codeView in codeViews{
codeView.size = codeViewSize
}
}
}
public init(codeCount:Int=6){
self.codeCount = codeCount
self.codeViews = (1...codeCount).map{ _ in CodeView(frame:.zero) }
for holder in self.codeViews{
holder.backgroundColor = .white
holder.textAlignment = .center
holder.textColor = UIColor.darkText
holder.clipsToBounds = true
holder.size = codeViewSize
holder.layer.cornerRadius = 4
holder.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.semibold)
stackView.addArrangedSubview(holder)
}
stackView.spacing = 8
stackView.alignment = .center
stackView.distribution = .equalSpacing
stackView.axis = .horizontal
hiddenTextField.text = ""
hiddenTextField.isHidden = true
super.init(frame: CGRect.zero)
commonInit()
}
var code:String{
return hiddenTextField.text ?? ""
}
var allOutlets :[UIView]{
return [hiddenTextField,stackView]
}
var allUITextFieldOutlets :[UITextField]{
return [hiddenTextField]
}
required public init?(coder aDecoder: NSCoder) {
fatalError("NotImplemented")
}
open func commonInit(){
for childView in allOutlets{
addSubview(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
}
installConstaints()
setupAttrs()
}
open func installConstaints(){
stackView.pac_edge(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))
hiddenTextField.pa_centerY.install()
hiddenTextField.pa_centerX.install()
hiddenTextField.pac_horizontal(0)
hiddenTextField.pa_height.eq(36).install()
}
open func setupAttrs(){
hiddenTextField.delegate = self
hiddenTextField.keyboardType = .numberPad
hiddenTextField.addTarget(self, action: #selector(onTextChanged), for: .editingChanged)
// hiddenTextField.isSecureTextEntry = true // 就算不可见也要设置,因为 UITextField 有全局广播通知
stackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onTap)))
layer.cornerRadius = 4
clipsToBounds = true
}
@objc func onTap(_ sender:AnyObject){
hiddenTextField.becomeFirstResponder()
}
open override var canBecomeFirstResponder : Bool {
return hiddenTextField.canBecomeFirstResponder
}
open override func becomeFirstResponder() -> Bool {
return hiddenTextField.becomeFirstResponder()
}
open override func resignFirstResponder() -> Bool {
return hiddenTextField.resignFirstResponder()
}
// MARK: UITextFieldDelegate
func updateVisiblCode(){
let chars = Array((hiddenTextField.text ?? "").characters)
for (index,codeView) in codeViews.enumerated(){
if index < chars.endIndex{
codeView.text = String(chars[index])
}else{
codeView.text = nil
}
}
}
public func clear(){
hiddenTextField.text = ""
updateVisiblCode()
}
open var didInputAllCode:((String) -> Void)?
@objc func onTextChanged(_ sender:AnyObject){
updateVisiblCode()
if code.characters.count == codeCount{
self.didInputAllCode?(code)
}
}
open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let code = textField.text ?? ""
let currentCount = code.characters.count
if range.length == 0 {
// append
return currentCount < codeCount
}else{
// delete
return true
}
}
}
| 0b9e0391814ab08cc8a87c0cf0931089 | 23.898204 | 132 | 0.693122 | false | false | false | false |
devincoughlin/swift | refs/heads/master | test/expr/cast/as_coerce.swift | apache-2.0 | 5 | // RUN: %target-typecheck-verify-swift -enable-objc-interop
// Test the use of 'as' for type coercion (which requires no checking).
@objc protocol P1 {
func foo()
}
class A : P1 {
@objc func foo() { }
}
@objc class B : A {
func bar() { }
}
func doFoo() {}
func test_coercion(_ a: A, b: B) {
// Coercion to a protocol type
let x = a as P1
x.foo()
// Coercion to a superclass type
let y = b as A
y.foo()
}
class C : B { }
class D : C { }
func prefer_coercion(_ c: inout C) {
let d = c as! D
c = d
}
// Coerce literals
var i32 = 1 as Int32
var i8 = -1 as Int8
// Coerce to a superclass with generic parameter inference
class C1<T> {
func f(_ x: T) { }
}
class C2<T> : C1<Int> { }
var c2 = C2<()>()
var c1 = c2 as C1
c1.f(5)
@objc protocol P {}
class CC : P {}
let cc: Any = CC()
if cc is P {
doFoo()
}
if let p = cc as? P {
doFoo()
_ = p
}
// Test that 'as?' coercion fails.
let strImplicitOpt: String! = nil
_ = strImplicitOpt as? String // expected-warning{{conditional downcast from 'String?' to 'String' does nothing}}{{19-30=}}
class C3 {}
class C4 : C3 {}
class C5 {}
var c: AnyObject = C3()
if let castX = c as! C4? {} // expected-error {{cannot downcast from 'AnyObject' to a more optional type 'C4?'}}
// Only suggest replacing 'as' with 'as!' if it would fix the error.
C3() as C4 // expected-error {{'C3' is not convertible to 'C4'; did you mean to use 'as!' to force downcast?}} {{6-8=as!}}
C3() as C5 // expected-error {{cannot convert value of type 'C3' to type 'C5' in coercion}}
// Diagnostic shouldn't include @lvalue in type of c3.
var c3 = C3()
c3 as C4 // expected-error {{'C3' is not convertible to 'C4'; did you mean to use 'as!' to force downcast?}} {{4-6=as!}}
// <rdar://problem/19495142> Various incorrect diagnostics for explicit type conversions
1 as Double as Float // expected-error{{cannot convert value of type 'Double' to type 'Float' in coercion}}
1 as Int as String // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}}
Double(1) as Double as String // expected-error{{cannot convert value of type 'Double' to type 'String' in coercion}}
["awd"] as [Int] // expected-error{{cannot convert value of type 'String' to expected element type 'Int'}}
([1, 2, 1.0], 1) as ([String], Int)
// expected-error@-1 2 {{cannot convert value of type 'Int' to expected element type 'String'}}
// expected-error@-2 {{cannot convert value of type 'Double' to expected element type 'String'}}
[[1]] as [[String]] // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}}
(1, 1.0) as (Int, Int) // expected-error{{cannot convert value of type 'Double' to type 'Int' in coercion}}
(1.0, 1, "asd") as (String, Int, Float) // expected-error{{cannot convert value of type 'Double' to type 'String' in coercion}}
(1, 1.0, "a", [1, 23]) as (Int, Double, String, [String])
// expected-error@-1 2 {{cannot convert value of type 'Int' to expected element type 'String'}}
_ = [1] as! [String] // expected-warning{{cast from '[Int]' to unrelated type '[String]' always fails}}
_ = [(1, (1, 1))] as! [(Int, (String, Int))] // expected-warning{{cast from '[(Int, (Int, Int))]' to unrelated type '[(Int, (String, Int))]' always fails}}
// <rdar://problem/19495253> Incorrect diagnostic for explicitly casting to the same type
_ = "hello" as! String // expected-warning{{forced cast of 'String' to same type has no effect}} {{13-24=}}
// <rdar://problem/19499340> QoI: Nimble as -> as! changes not covered by Fix-Its
func f(_ x : String) {}
f("what" as Any as String) // expected-error {{'Any' is not convertible to 'String'; did you mean to use 'as!' to force downcast?}} {{17-19=as!}}
f(1 as String) // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}}
// <rdar://problem/19650402> Swift compiler segfaults while running the annotation tests
let s : AnyObject = C3()
s as C3 // expected-error{{'AnyObject' is not convertible to 'C3'; did you mean to use 'as!' to force downcast?}} {{3-5=as!}}
// SR-6022
func sr6022() -> Any { return 0 }
func sr6022_1() { return; }
protocol SR6022_P {}
_ = sr6022 as! SR6022_P // expected-warning {{cast from '() -> Any' to unrelated type 'SR6022_P' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'?}}{{11-11=()}}
_ = sr6022 as? SR6022_P // expected-warning {{cast from '() -> Any' to unrelated type 'SR6022_P' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'}}{{11-11=()}}
_ = sr6022_1 as! SR6022_P // expected-warning {{cast from '() -> ()' to unrelated type 'SR6022_P' always fails}}
_ = sr6022_1 as? SR6022_P // expected-warning {{cast from '() -> ()' to unrelated type 'SR6022_P' always fails}}
func testSR6022_P<T: SR6022_P>(_: T.Type) {
_ = sr6022 as! T // expected-warning {{cast from '() -> Any' to unrelated type 'T' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'?}}{{13-13=()}}
_ = sr6022 as? T // expected-warning {{cast from '() -> Any' to unrelated type 'T' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'?}}{{13-13=()}}
_ = sr6022_1 as! T // expected-warning {{cast from '() -> ()' to unrelated type 'T' always fails}}
_ = sr6022_1 as? T // expected-warning {{cast from '() -> ()' to unrelated type 'T' always fails}}
}
func testSR6022_P_1<U>(_: U.Type) {
_ = sr6022 as! U // Okay
_ = sr6022 as? U // Okay
_ = sr6022_1 as! U // Okay
_ = sr6022_1 as? U // Okay
}
_ = sr6022 as! AnyObject // expected-warning {{forced cast from '() -> Any' to 'AnyObject' always succeeds; did you mean to use 'as'?}}
_ = sr6022 as? AnyObject // expected-warning {{conditional cast from '() -> Any' to 'AnyObject' always succeeds}}
_ = sr6022_1 as! Any // expected-warning {{forced cast from '() -> ()' to 'Any' always succeeds; did you mean to use 'as'?}}
_ = sr6022_1 as? Any // expected-warning {{conditional cast from '() -> ()' to 'Any' always succeeds}}
| 9215b184163f6475dfef7a668f91bb31 | 42.540146 | 185 | 0.642414 | false | false | false | false |
Legoless/iOS-Course | refs/heads/master | 2015-1/Lesson15/MyWeather/MyWeather/WeatherLoadOperation.swift | mit | 1 | //
// WeatherLoadOperation.swift
// MyWeather
//
// Created by Dal Rupnik on 29/11/15.
// Copyright © 2015 Unified Sense. All rights reserved.
//
import Foundation
let APIKey = ""
class WeatherLoadOperation: NSOperation {
var location = ""
// Called when completed with parsed temperature as double, parsed weather icon and any object JSON
var completionHandler : ((Double, WeatherIcon, AnyObject) -> Void)?
override func main () -> Void {
let request = NSMutableURLRequest()
request.URL = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?units=metric&appid=" + APIKey + "&q=" + location.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet())!)!
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil || data == nil {
return
}
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as! [String : AnyObject]
let weather = JSON["main"]!
let description = JSON["weather"]![0]["description"] as! String
var icon : WeatherIcon = .Sunny
if description.containsString("cloud") {
icon = .Cloudy
}
else if description.containsString("fog") {
icon = .Fog
}
else if description.containsString("drizzle") {
icon = .Showers
}
else if description.containsString("rain") {
icon = .Rain
}
else if description.containsString("snow") {
icon = .Sunny
}
else if description.containsString("thunder") {
icon = .Thunder
}
let temperature = weather as! [String : AnyObject]
if let temp = temperature["temp"] as? NSNumber {
if let completionHandler = self.completionHandler {
completionHandler(temp.doubleValue, icon, weather)
}
}
}
catch {
}
}
task.resume()
}
}
| 0439d9e5161398f3b29b149e90f6324c | 32.455696 | 229 | 0.493757 | false | false | false | false |
IngmarStein/swift | refs/heads/master | test/expr/cast/nil_value_to_optional.swift | apache-2.0 | 4 | // RUN: %target-parse-verify-swift
var t = true
var f = false
func markUsed<T>(_ t: T) {}
markUsed(t != nil) // expected-warning {{comparing non-optional value of type 'Bool' to nil always returns true}}
markUsed(f != nil) // expected-warning {{comparing non-optional value of type 'Bool' to nil always returns true}}
class C : Equatable {}
func == (lhs: C, rhs: C) -> Bool {
return true
}
func test(_ c: C) {
if c == nil {} // expected-warning {{comparing non-optional value of type 'C' to nil always returns false}}
}
class D {}
var d = D()
var dopt: D? = nil
var diuopt: D! = nil
_ = d! // expected-error {{cannot force unwrap value of non-optional type 'D'}}
_ = dopt == nil
_ = diuopt == nil
| 1aa6b784f628653798d7e85e59c3157d | 23.517241 | 113 | 0.642757 | false | false | false | false |
Ge3kXm/MXWB | refs/heads/master | MXWB/Classes/Home/Popover/MXTransitionManager.swift | apache-2.0 | 1 | //
// MXTransitionManager.swift
// MXWB
//
// Created by maRk'sTheme on 2017/4/14.
// Copyright © 2017年 maRk. All rights reserved.
//
import UIKit
class MXTransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
// 标志,为了判断转场动画中的fromView,和toView
var isPresented = false
// 存放presnetView的frame
var presentViewFrame: CGRect?
// MARK: -- UIViewControllerTransitioningDelegate
// 返回一个负责转场动画的对象
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController?
{
let pc = MXTransitionController(presentedViewController: presented, presenting: source)
pc.presentedViewFrame = presentViewFrame
return pc
}
// 返回一个管理弹出的对象
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning?
{
NotificationCenter.default.post(name: NSNotification.Name(rawValue: MXWB_NOTIFICATION_TRANSITIONMANAGER_DIDPRESENTED), object: self)
isPresented = true
return self
}
// 返回一个管理消失的对象
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?
{
NotificationCenter.default.post(name: NSNotification.Name(rawValue: MXWB_NOTIFICATION_TRANSITIONMANAGER_DIDDISMISSED), object: self)
isPresented = false
return self
}
// MARK: -- UIViewControllerAnimatedTransitioning
// 动画时长
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval
{
return 0.25
}
// 实现该方法,系统就不会出现默认的转场动画,所有动画都需要自己实现,所有的东西都在transitionContext中
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if isPresented {
willPresentController(transitionContext: transitionContext)
}else {
willDismissController(transitionContext: transitionContext)
}
}
private func willPresentController(transitionContext: UIViewControllerContextTransitioning)
{
guard let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) else {
return
}
let containerView = transitionContext.containerView
containerView.addSubview(toView)
// 动画实现菜单的弹出
toView.transform = CGAffineTransform(scaleX: 1.0, y: 0)
toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
toView.transform = CGAffineTransform.identity
}) { (_) in
// 完成动画后必须要调用该方法
transitionContext.completeTransition(true)
}
}
private func willDismissController(transitionContext: UIViewControllerContextTransitioning)
{
guard let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from) else {
return
}
fromView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
fromView.transform = CGAffineTransform(scaleX: 1.0, y: 0.00001)
}, completion: { (_) in
fromView.removeFromSuperview()
// 完成动画后必须要调用该方法
transitionContext.completeTransition(true)
})
}
}
| 9caf9b16efd38665d314810dc7272305 | 36.357895 | 168 | 0.695407 | false | false | false | false |
Jnosh/swift | refs/heads/master | test/DebugInfo/letstring.swift | apache-2.0 | 13 | // RUN: %target-swift-frontend %s -emit-ir -g -o %t.ll
// RUN: %FileCheck %s < %t.ll
class UIWindow {}
class AppDelegate {
var window: UIWindow?
// CHECK: define hidden {{.*}}i1 {{.*}}11AppDelegateC1f
func f() -> Bool {
// Test for -O0 shadow copies.
// CHECK: call void @llvm.dbg.declare({{.*}}, metadata ![[SELF:.*]], metadata !{{[0-9]+}})
// CHECK-NOT: call void @llvm.dbg.value
// CHECK: call void @llvm.dbg.declare({{.*}}, metadata ![[A:.*]], metadata !{{[0-9]+}})
let a = "let"
// CHECK-NOT: call void @llvm.dbg.value
// CHECK: call void @llvm.dbg.declare({{.*}}, metadata ![[B:.*]], metadata !{{[0-9]+}})
// CHECK-NOT: call void @llvm.dbg.value
// CHECK: ret
// CHECK-DAG: ![[SELF]] = !DILocalVariable(name: "self", arg: 1{{.*}} line: [[@LINE-10]],
// CHECK-DAG: ![[A]] = !DILocalVariable(name: "a",{{.*}} line: [[@LINE-6]],
// CHECK-DAG: ![[B]] = !DILocalVariable(name: "b",{{.*}} line: [[@LINE+1]],
var b = "var"
self.window = UIWindow()
return true
}
}
// End-to-end test:
// RUN: llc %t.ll -filetype=obj -o %t.o
// RUN: %llvm-dwarfdump %t.o | %FileCheck %s --check-prefix DWARF-CHECK
// DWARF-CHECK: DW_AT_name {{.*}} "f"
//
// DWARF-CHECK: DW_TAG_formal_parameter
// DWARF-CHECK: DW_AT_name {{.*}} "self"
//
// DWARF-CHECK: DW_TAG_variable
// DWARF-CHECK: DW_AT_name {{.*}} "a"
//
// DWARF-CHECK: DW_TAG_variable
// DWARF-CHECK: DW_AT_name {{.*}} "b"
| 69e9bfea938c408911b0fd4b22040afd | 35.871795 | 94 | 0.556328 | false | true | false | false |
jlieske/chartable | refs/heads/master | chartable.swift | gpl-3.0 | 1 | //
// main.swift
// CharTable
//
// Created by Jay Lieske on 2014.11.14.
// Copyright (c) 2014 Jay Lieske. All rights reserved.
//
import Foundation
func usage() {
println("chartable [character set name] >table.md")
println("Generates a Markdown file with a table listing the characters")
println("that in the named character set.")
println("Allowed values for character set name:")
println(" operators: Swift language operator head characters")
println(" letters: NSCharacterSet.letterCharacterSet")
println(" punctuation: NSCharacterSet.punctuationCharacterSet")
println(" symbols: NSCharacterSet.symbolCharacterSet")
println(" sympunct: symbols ∪ punctuation")
}
if Process.arguments.count < 2 {
usage()
exit(2)
}
extension UnicodeScalar {
var intValue: Int { get {return Int(self.value)} }
}
extension NSMutableCharacterSet {
func addCharacter(i: Int) {
self.addCharactersInRange(NSMakeRange(i, 1))
}
func addCharacter(ch: UnicodeScalar) {
self.addCharactersInRange(NSMakeRange(ch.intValue, 1))
}
}
extension NSCharacterSet {
func unionWithCharacterSet(otherSet: NSCharacterSet) -> NSCharacterSet {
let set: NSMutableCharacterSet = self.mutableCopy() as NSMutableCharacterSet
set.formUnionWithCharacterSet(otherSet)
return set.copy() as NSMutableCharacterSet
}
}
/// Character set of Swift operator-head characters.
func swiftOperatorHeadCharacterSet() -> NSCharacterSet {
let cset = NSMutableCharacterSet()
// operator-head → / = - + ! * % < > & | ^ ~ ?
cset.addCharactersInString("/=-+!*%<>&|^~?")
// operator-head → U+00A1–U+00A7
cset.addCharactersInRange(NSRange(0xA1...0xA7))
// operator-head → U+00A9 or U+00AB
cset.addCharacter(0xA9)
cset.addCharacter(0xAB)
// operator-head → U+00AC or U+00AE
cset.addCharacter(0xAC)
cset.addCharacter(0xAE)
// operator-head → U+00B0–U+00B1, U+00B6, U+00BB, U+00BF, U+00D7, or U+00F7
cset.addCharactersInRange(NSRange(0xB0...0xB1))
cset.addCharacter(0xB6)
cset.addCharacter(0xBB)
cset.addCharacter(0xBF)
cset.addCharacter(0xD7)
cset.addCharacter(0xF7)
// operator-head → U+2016–U+2017 or U+2020–U+2027
cset.addCharactersInRange(NSRange(0x2016...0x2017))
cset.addCharactersInRange(NSRange(0x2020...0x2027))
// operator-head → U+2030–U+203E
cset.addCharactersInRange(NSRange(0x2030...0x203E))
// operator-head → U+2041–U+2053
cset.addCharactersInRange(NSRange(0x2041...0x2053))
// operator-head → U+2055–U+205E
cset.addCharactersInRange(NSRange(0x2055...0x205E))
// operator-head → U+2190–U+23FF
cset.addCharactersInRange(NSRange(0x2190...0x23FF))
// operator-head → U+2500–U+2775
cset.addCharactersInRange(NSRange(0x2500...0x2775))
// operator-head → U+2794–U+2BFF
cset.addCharactersInRange(NSRange(0x2794...0x2BFF))
// operator-head → U+2E00–U+2E7F
cset.addCharactersInRange(NSRange(0x2E00...0x2E7F))
// operator-head → U+3001–U+3003
cset.addCharactersInRange(NSRange(0x3001...0x3003))
// operator-head → U+3008–U+3030
cset.addCharactersInRange(NSRange(0x3008...0x3030))
// dot-operator-head → ..
cset.addCharacter(".")
return cset.copy() as NSCharacterSet
}
// Pick the character set from the command-line arg.
let charsetName = Process.arguments[1]
let (charset: NSCharacterSet, title: String) = {
switch (charsetName) {
case "operators":
return (swiftOperatorHeadCharacterSet(), "Swift Operator Head")
case "letters":
return (NSCharacterSet.letterCharacterSet(), "Letters")
case "punctuation":
return (NSCharacterSet.punctuationCharacterSet(), "Punctuation")
case "symbols":
return (NSCharacterSet.symbolCharacterSet(), "Symbols")
case "sympunct":
return (NSCharacterSet.symbolCharacterSet()
.unionWithCharacterSet(NSCharacterSet.punctuationCharacterSet()),
"Symbols and Punctuation")
case let name:
println("Unknown character set name: \(name)")
usage()
exit(3)
}
}()
let charsetBits = charset.bitmapRepresentation
/// Extension for NSData to treat bytes as integers.
extension NSData {
/// Treat the data as an array of UInt16 values, and return the index'th one.
func uint16AtIndex(index: Int) -> UInt16 {
var word: UInt16 = 0
self.getBytes(&word, range: NSMakeRange(index*2, sizeofValue(word)))
return word
}
/// Treat the data as an array of 16-bit values, and return the count.
var count16: Int { get {
return self.length / 2 // round down, ignore incomplete values at end
} }
}
/// Return the character for a row and column in the table.
func bitChar(base: UInt32, bits: UInt16, column: UInt16) -> UnicodeScalar? {
let mask = 1 << column
if mask & bits == 0 {
return nil
} else {
return UnicodeScalar(base+UInt32(column))
}
}
// Returns HTML entity for characters that need escaping.
func escape(c: UnicodeScalar) -> String {
switch c {
case "&": return "&"
case "<": return "<"
case ">": return ">"
default: return String(c)
}
}
// Generate Markdown header.
println("# \(title)")
// Generate HTML table with characters.
println("<table><thead><tr><th></th>")
println("<th>0</th><th>1</th><th>2</th><th>3</th>")
println("<th>4</th><th>5</th><th>6</th><th>7</th>")
println("<th>8</th><th>9</th><th>A</th><th>B</th>")
println("<th>C</th><th>D</th><th>E</th><th>F</th>")
println("</tr></thead><tbody>")
for i in 0..<charsetBits.count16 {
let bits = charsetBits.uint16AtIndex(i)
if bits != 0 {
let row = UInt32(i) * 16
let hex = String(format: "%X", row)
println("<tr><th>\(hex)</th>")
//autoreleasepool {
for col: UInt16 in 0...15 {
if let ch = bitChar(row, bits, col) {
let s = escape(ch)
print("<td>\(s)</td>")
}
else {
print("<td></td>")
}
}
//}
println("</tr>")
}
}
println("</tbody></table>")
| c39ef6885dfbf7fbe05f15b9d252f53d | 32.128342 | 84 | 0.642454 | false | false | false | false |
anthonyApptist/Poplur | refs/heads/master | Poplur/Video.swift | apache-2.0 | 1 | //
// Video.swift
// Poplur
//
// Created by Anthony Ma on 3/2/2017.
// Copyright © 2017 Apptist. All rights reserved.
//
import Foundation
class Video: NSObject {
enum Category: String {
case music = "music"
case lifestyle = "lifestyle"
}
// Properties
var category: Category
var likes: Int
var locationPosted: String
var postedBy: String
var url: URL
var watchedBy: NSArray?
var watchedFrom: NSArray?
init(category: Category, likes: Int, locationPosted: String, postedBy: String, url: URL) {
self.category = category
self.likes = likes
self.locationPosted = locationPosted
self.postedBy = postedBy
self.url = url
}
// return postedBy and location
}
| 6430e33d763b33c1243535c48c3cf519 | 18.756098 | 94 | 0.598765 | false | false | false | false |
JaySonGD/SwiftDayToDay | refs/heads/master | 获取系统通信录1/获取系统通信录1/ViewController.swift | mit | 1 | //
// ViewController.swift
// 获取系统通信录1
//
// Created by czljcb on 16/3/18.
// Copyright © 2016年 lQ. All rights reserved.
//
import UIKit
import AddressBookUI
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let VC = ABPeoplePickerNavigationController()
VC.peoplePickerDelegate = self
presentViewController(VC, animated: true, completion: nil)
}
}
extension ViewController: ABPeoplePickerNavigationControllerDelegate{
func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord) {
print(person)
let name = (ABRecordCopyValue(person, kABPersonLastNameProperty).takeRetainedValue() as! String) + (ABRecordCopyValue(person, kABPersonFirstNameProperty).takeRetainedValue() as! String)
let phones: ABMultiValueRef = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue() as ABMultiValueRef
let count = ABMultiValueGetCount(phones)
print(name)
for i in 0..<count {
print( ABMultiValueCopyLabelAtIndex(phones, i).takeRetainedValue())
print( ABMultiValueCopyValueAtIndex(phones, i).takeRetainedValue())
}
}
// func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord, property: ABPropertyID, identifier: ABMultiValueIdentifier) {
//
// print(person,property,identifier)
// }
} | 82de08f5a58803ff3049bc8a6ffd4ab1 | 33.254902 | 193 | 0.699885 | false | false | false | false |
Adlai-Holler/Flux.swift | refs/heads/master | Examples/TodoMVC/TodoMVC/TodoItem.swift | mit | 1 | //
// TodoItem.swift
// TodoMVC
//
// Created by Adlai Holler on 2/6/16.
// Copyright © 2016 Adlai Holler. All rights reserved.
//
import CoreData
typealias TodoItemID = Int64
struct TodoItem {
static let entityName = "TodoItem"
enum Property: String {
case title
case id
case completed
case softDeleted
}
var id: TodoItemID
/// This is nil if the object was not created from an NSManagedObject.
let objectID: NSManagedObjectID?
var title: String?
var completed: Bool
var softDeleted: Bool
init(id: TodoItemID, title: String?, completed: Bool) {
self.id = id
self.objectID = nil
self.title = title
self.completed = completed
self.softDeleted = false
}
init(object: NSManagedObject) {
assert(object.entity.name == TodoItem.entityName)
title = object.valueForKey(Property.title.rawValue) as! String?
completed = object.valueForKey(Property.completed.rawValue) as! Bool
id = (object.valueForKey(Property.id.rawValue) as! NSNumber).longLongValue
softDeleted = object.valueForKey(Property.softDeleted.rawValue) as! Bool
objectID = object.objectID
}
func apply(object: NSManagedObject) {
guard object.entity.name == TodoItem.entityName else {
assertionFailure()
return
}
let idObj = NSNumber(longLong: id)
if object.valueForKey(Property.id.rawValue) as! NSNumber? != idObj {
object.setValue(idObj, forKey: Property.id.rawValue)
}
if object.valueForKey(Property.title.rawValue) as! String? != title {
object.setValue(title, forKey: Property.title.rawValue)
}
if object.valueForKey(Property.completed.rawValue) as! Bool != completed {
object.setValue(completed, forKey: Property.completed.rawValue)
}
if object.valueForKey(Property.softDeleted.rawValue) as! Bool != softDeleted {
object.setValue(softDeleted, forKey: Property.softDeleted.rawValue)
}
}
}
extension TodoItem {
static var maxId: TodoItemID {
let storedValue = TodoItemID(NSUserDefaults.standardUserDefaults().integerForKey("TodoItemMaxID"))
return storedValue == 0 ? 1 : storedValue
}
static func incrementMaxID() {
let newValue = maxId + 1
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(Int(newValue), forKey: "TodoItemMaxID")
defaults.synchronize()
}
} | eb4be74bfb29194a59c707cea5a40dcf | 30.555556 | 106 | 0.651272 | false | false | false | false |
huonw/swift | refs/heads/master | validation-test/stdlib/Algorithm.swift | apache-2.0 | 3 | // -*- swift -*-
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
import StdlibCollectionUnittest
import SwiftPrivate
var Algorithm = TestSuite("Algorithm")
// FIXME(prext): remove this conformance.
extension String.UnicodeScalarView : Equatable {}
// FIXME(prext): remove this function.
public func == (
lhs: String.UnicodeScalarView, rhs: String.UnicodeScalarView) -> Bool {
return Array(lhs) == Array(rhs)
}
// FIXME(prext): move this struct to the point of use.
Algorithm.test("min,max") {
// Identities are unique in this set.
let a1 = MinimalComparableValue(0, identity: 1)
let a2 = MinimalComparableValue(0, identity: 2)
let a3 = MinimalComparableValue(0, identity: 3)
let b1 = MinimalComparableValue(1, identity: 4)
let b2 = MinimalComparableValue(1, identity: 5)
let b3 = MinimalComparableValue(1, identity: 6)
let c1 = MinimalComparableValue(2, identity: 7)
let c2 = MinimalComparableValue(2, identity: 8)
let c3 = MinimalComparableValue(2, identity: 9)
// 2-arg min()
expectEqual(a1.identity, min(a1, b1).identity)
expectEqual(a1.identity, min(b1, a1).identity)
expectEqual(a1.identity, min(a1, a2).identity)
// 2-arg max()
expectEqual(c1.identity, max(c1, b1).identity)
expectEqual(c1.identity, max(b1, c1).identity)
expectEqual(c1.identity, max(c2, c1).identity)
// 3-arg min()
expectEqual(a1.identity, min(a1, b1, c1).identity)
expectEqual(a1.identity, min(b1, a1, c1).identity)
expectEqual(a1.identity, min(c1, b1, a1).identity)
expectEqual(a1.identity, min(c1, a1, b1).identity)
expectEqual(a1.identity, min(a1, a2, a3).identity)
expectEqual(a1.identity, min(a1, a2, b1).identity)
expectEqual(a1.identity, min(a1, b1, a2).identity)
expectEqual(a1.identity, min(b1, a1, a2).identity)
// 3-arg max()
expectEqual(c1.identity, max(c1, b1, a1).identity)
expectEqual(c1.identity, max(a1, c1, b1).identity)
expectEqual(c1.identity, max(b1, a1, c1).identity)
expectEqual(c1.identity, max(b1, c1, a1).identity)
expectEqual(c1.identity, max(c3, c2, c1).identity)
expectEqual(c1.identity, max(c2, c1, b1).identity)
expectEqual(c1.identity, max(c2, b1, c1).identity)
expectEqual(c1.identity, max(b1, c2, c1).identity)
// 4-arg min()
expectEqual(a1.identity, min(a1, b1, a2, b2).identity)
expectEqual(a1.identity, min(b1, a1, a2, b2).identity)
expectEqual(a1.identity, min(c1, b1, b2, a1).identity)
expectEqual(a1.identity, min(c1, b1, a1, a2).identity)
// 4-arg max()
expectEqual(c1.identity, max(c2, b1, c1, b2).identity)
expectEqual(c1.identity, max(b1, c2, c1, b2).identity)
expectEqual(c1.identity, max(a1, b1, b2, c1).identity)
expectEqual(c1.identity, max(a1, b1, c2, c1).identity)
}
Algorithm.test("sorted/strings") {
expectEqual(
["Banana", "apple", "cherry"],
["apple", "Banana", "cherry"].sorted())
let s = ["apple", "Banana", "cherry"].sorted() {
$0.characters.count > $1.characters.count
}
expectEqual(["Banana", "cherry", "apple"], s)
}
// A wrapper around Array<T> that disables any type-specific algorithm
// optimizations and forces bounds checking on.
struct A<T> : MutableCollection, RandomAccessCollection {
typealias Indices = CountableRange<Int>
init(_ a: Array<T>) {
impl = a
}
var startIndex: Int {
return 0
}
var endIndex: Int {
return impl.count
}
func makeIterator() -> Array<T>.Iterator {
return impl.makeIterator()
}
subscript(i: Int) -> T {
get {
expectTrue(i >= 0 && i < impl.count)
return impl[i]
}
set (x) {
expectTrue(i >= 0 && i < impl.count)
impl[i] = x
}
}
subscript(r: Range<Int>) -> Array<T>.SubSequence {
get {
expectTrue(r.lowerBound >= 0 && r.lowerBound <= impl.count)
expectTrue(r.upperBound >= 0 && r.upperBound <= impl.count)
return impl[r]
}
set (x) {
expectTrue(r.lowerBound >= 0 && r.lowerBound <= impl.count)
expectTrue(r.upperBound >= 0 && r.upperBound <= impl.count)
impl[r] = x
}
}
var impl: Array<T>
}
func randomArray() -> A<Int> {
let count = Int(rand32(exclusiveUpperBound: 50))
return A(randArray(count))
}
Algorithm.test("invalidOrderings") {
withInvalidOrderings {
var a = randomArray()
_blackHole(a.sorted(by: $0))
}
withInvalidOrderings {
var a: A<Int>
a = randomArray()
let lt = $0
let first = a.first
_ = a.partition(by: { !lt($0, first!) })
}
/*
// FIXME: Disabled due to <rdar://problem/17734737> Unimplemented:
// abstraction difference in l-value
withInvalidOrderings {
var a = randomArray()
var pred = $0
_insertionSort(&a, a.indices, &pred)
}
*/
}
// The routine is based on http://www.cs.dartmouth.edu/~doug/mdmspe.pdf
func makeQSortKiller(_ len: Int) -> [Int] {
var candidate: Int = 0
var keys = [Int: Int]()
func Compare(_ x: Int, y : Int) -> Bool {
if keys[x] == nil && keys[y] == nil {
if (x == candidate) {
keys[x] = keys.count
} else {
keys[y] = keys.count
}
}
if keys[x] == nil {
candidate = x
return true
}
if keys[y] == nil {
candidate = y
return false
}
return keys[x]! > keys[y]!
}
var ary = [Int](repeating: 0, count: len)
var ret = [Int](repeating: 0, count: len)
for i in 0..<len { ary[i] = i }
ary = ary.sorted(by: Compare)
for i in 0..<len {
ret[ary[i]] = i
}
return ret
}
Algorithm.test("sorted/complexity") {
var ary: [Int] = []
// Check performance of sorting an array of repeating values.
var comparisons_100 = 0
ary = [Int](repeating: 0, count: 100)
ary.sort { comparisons_100 += 1; return $0 < $1 }
var comparisons_1000 = 0
ary = [Int](repeating: 0, count: 1000)
ary.sort { comparisons_1000 += 1; return $0 < $1 }
expectTrue(comparisons_1000/comparisons_100 < 20)
// Try to construct 'bad' case for quicksort, on which the algorithm
// goes quadratic.
comparisons_100 = 0
ary = makeQSortKiller(100)
ary.sort { comparisons_100 += 1; return $0 < $1 }
comparisons_1000 = 0
ary = makeQSortKiller(1000)
ary.sort { comparisons_1000 += 1; return $0 < $1 }
expectTrue(comparisons_1000/comparisons_100 < 20)
}
Algorithm.test("sorted/return type") {
let x: Array = ([5, 4, 3, 2, 1] as ArraySlice).sorted()
}
Algorithm.test("sort3/simple")
.forEach(in: [
[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]
]) {
var input = $0
_sort3(&input, 0, 1, 2)
expectEqual([1, 2, 3], input)
}
func isSorted<T>(_ a: [T], by areInIncreasingOrder: (T, T) -> Bool) -> Bool {
return !a.dropFirst().enumerated().contains(where: { (offset, element) in
areInIncreasingOrder(element, a[offset])
})
}
Algorithm.test("sort3/stable")
.forEach(in: [
[1, 1, 2], [1, 2, 1], [2, 1, 1], [1, 2, 2], [2, 1, 2], [2, 2, 1], [1, 1, 1]
]) {
// decorate with offset, but sort by value
var input = Array($0.enumerated())
_sort3(&input, 0, 1, 2) { $0.element < $1.element }
// offsets should still be ordered for equal values
expectTrue(isSorted(input) {
if $0.element == $1.element {
return $0.offset < $1.offset
}
return $0.element < $1.element
})
}
runAllTests()
| dbf3f417f19328d415c379e03b6778a4 | 27.335938 | 79 | 0.6311 | false | false | false | false |
Burning-Man-Earth/iBurn-iOS | refs/heads/master | iBurn/UITableView+iBurn.swift | mpl-2.0 | 1 | //
// UITableView+iBurn.swift
// iBurn
//
// Created by Chris Ballinger on 7/30/18.
// Copyright © 2018 Burning Man Earth. All rights reserved.
//
import Foundation
extension UITableView {
public static func iBurnTableView(style: UITableView.Style = .plain) -> UITableView {
let tableView = UITableView(frame: .zero, style: style)
tableView.setDataObjectDefaults()
return tableView
}
public func setDataObjectDefaults() {
registerCustomCellClasses()
estimatedRowHeight = 120
rowHeight = UITableView.automaticDimension
}
/** Registers custom cell classes for BRC data objects */
@objc public func registerCustomCellClasses() {
let mapping = BRCDataObjectTableViewCell.cellIdentifiers
mapping.forEach { cellIdentifier, cellClass in
let nibName = NSStringFromClass(cellClass);
let nib = UINib.init(nibName: nibName, bundle: nil)
self.register(nib, forCellReuseIdentifier: cellIdentifier)
}
}
}
| 00954b1b7f1362f42b1da1073696f7ca | 29.705882 | 89 | 0.673372 | false | false | false | false |
wireapp/wire-ios | refs/heads/develop | Wire-iOS/Sources/Analytics/Events/ZMConversation+Analytics.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireDataModel
enum ConversationType: Int {
case oneToOne
case group
}
extension ConversationType {
var analyticsTypeString: String {
switch self {
case .oneToOne: return "one_to_one"
case .group: return "group"
}
}
static func type(_ conversation: ZMConversation) -> ConversationType? {
switch conversation.conversationType {
case .oneOnOne:
return .oneToOne
case .group:
return .group
default:
return nil
}
}
}
extension ZMConversation {
var analyticsTypeString: String? {
return ConversationType.type(self)?.analyticsTypeString
}
/// TODO: move to DM
/// Whether the conversation is a 1-on-1 conversation with a service user
var isOneOnOneServiceUserConversation: Bool {
guard self.localParticipants.count == 2,
let otherUser = firstActiveParticipantOtherThanSelf else {
return false
}
return otherUser.serviceIdentifier != nil &&
otherUser.providerIdentifier != nil
}
/// TODO: move to DM
/// Whether the conversation includes at least 1 service user.
var includesServiceUser: Bool {
let participants = Array(localParticipants)
return participants.any { $0.isServiceUser }
}
var attributesForConversation: [String: Any] {
let participants = sortedActiveParticipants
let attributes: [String: Any] = [
"conversation_type": analyticsTypeString ?? "invalid",
"with_service": includesServiceUser ? true : false,
"is_allow_guests": accessMode == ConversationAccessMode.allowGuests ? true : false,
"conversation_size": participants.count.logRound(),
"is_global_ephemeral": hasSyncedMessageDestructionTimeout,
"conversation_services": sortedServiceUsers.count.logRound(),
"conversation_guests_wireless": participants.filter({
$0.isWirelessUser && $0.isGuest(in: self)
}).count.logRound(),
"conversation_guests_pro": participants.filter({
$0.isGuest(in: self) && $0.hasTeam
}).count.logRound()]
return attributes.updated(other: guestAttributes)
}
var guestAttributes: [String: Any] {
let numGuests = sortedActiveParticipants.filter({
$0.isGuest(in: self)
}).count
return [
"conversation_guests": numGuests.logRound(),
"user_type": SelfUser.current.isGuest(in: self) ? "guest" : "user"
]
}
}
| eaf1511a992cbcfe1a08dbe8d4e1a78a | 31.572816 | 95 | 0.640238 | false | false | false | false |
LoganWright/vapor | refs/heads/master | Sources/Vapor/Node/NodeInitializable.swift | mit | 1 | /**
* An umbrella protocol used to define behavior to and from Json
*/
public protocol NodeInitializable {
/**
This function will be used to create an instance of the type from Json
- parameter json: the json to use in initialization
- throws: a potential error. ie: invalid json type
- returns: an initialized object
*/
static func make(with node: Node) throws -> Self
}
// MARK: String
extension String: NodeInitializable {
/**
Make new instance if possible w/ given Node
- parameter node: node to create with
- throws: an error if creation fails
- returns: valid instance of 'Self' if possible
*/
public static func make(with node: Node) throws -> String {
guard let string = node.string else {
throw NodeError.UnableToConvert(node: node, toType: "\(self.dynamicType)")
}
return string
}
}
// MARK: Boolean
extension Bool: NodeInitializable {
/**
Make new instance if possible w/ given Node
- parameter node: node to create with
- throws: an error if creation fails
- returns: valid instance of 'Self' if possible
*/
public static func make(with node: Node) throws -> Bool {
guard let bool = node.bool else {
throw NodeError.UnableToConvert(node: node, toType: "\(self.dynamicType)")
}
return bool
}
}
// MARK: UnsignedIntegerType
extension UInt: NodeInitializable {}
extension UInt8: NodeInitializable {}
extension UInt16: NodeInitializable {}
extension UInt32: NodeInitializable {}
extension UInt64: NodeInitializable {}
extension UnsignedInteger {
/**
Make new instance if possible w/ given Node
- parameter node: node to create with
- throws: an error if creation fails
- returns: valid instance of 'Self' if possible
*/
public static func make(with node: Node) throws -> Self {
guard let int = node.uint else {
throw NodeError.UnableToConvert(node: node, toType: "\(self.dynamicType)")
}
return self.init(int.toUIntMax())
}
}
// MARK: SignedIntegerType
extension Int: NodeInitializable {}
extension Int8: NodeInitializable {}
extension Int16: NodeInitializable {}
extension Int32: NodeInitializable {}
extension Int64: NodeInitializable {}
extension SignedInteger {
/**
Make new instance if possible w/ given Node
- parameter node: node to create with
- throws: an error if creation fails
- returns: valid instance of 'Self' if possible
*/
public static func make(with node: Node) throws -> Self {
guard let int = node.int else {
throw NodeError.UnableToConvert(node: node, toType: "\(self.dynamicType)")
}
return self.init(int.toIntMax())
}
}
// MARK: FloatingPointType
extension Float: NodeInitializable {
/**
Make new instance if possible w/ given Node
- parameter node: node to create with
- throws: an error if creation fails
- returns: valid instance of 'Self' if possible
*/
public static func make(with node: Node) throws -> Float {
guard let float = node.float else {
throw NodeError.UnableToConvert(node: node, toType: "\(self.dynamicType)")
}
return self.init(float)
}
}
extension Double: NodeInitializable {
/**
Make new instance if possible w/ given Node
- parameter node: node to create with
- throws: an error if creation fails
- returns: valid instance of 'Self' if possible
*/
public static func make(with node: Node) throws -> Double {
guard let double = node.double else {
throw NodeError.UnableToConvert(node: node, toType: "\(self.dynamicType)")
}
return self.init(double)
}
}
public protocol NodeConvertibleFloatingPointType: NodeInitializable {
var doubleValue: Double { get }
init(_ other: Double)
}
| 6edc6058e1afa4909147a0ed00d14b99 | 23.689441 | 86 | 0.649811 | false | false | false | false |
yanif/circator | refs/heads/master | MetabolicCompass/DataSources/AdditionalInfoDataSource.swift | apache-2.0 | 1 | //
// AdditionalInfoDataSource.swift
// MetabolicCompass
//
// Created by Anna Tkach on 4/28/16.
// Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved.
//
import UIKit
import MetabolicCompassKit
let AdditionalInfoFont = UIFont(name: "GothamBook", size: 16.0)!
let AdditionalInfoUnitsFont = UIFont(name: "GothamBook", size: 12.0)!
class HeaderView: UICollectionReusableView {
@IBOutlet weak var titleLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
titleLbl.font = ScreenManager.appFontOfSize(15)
}
}
public class AdditionalInfoDataSource: BaseDataSource {
let model = AdditionalInfoModel()
var editMode = true
private let titledInputCellIdentifier = "titledInputCell"
private let scrollSelectionCellIdentifier = "scrollSelectionCell"
override func registerCells() {
let loadImageCellNib = UINib(nibName: "TitledInputCollectionViewCell", bundle: nil)
collectionView?.registerNib(loadImageCellNib, forCellWithReuseIdentifier: titledInputCellIdentifier)
let scrollSelectionCellNib = UINib(nibName: "ScrollSelectionViewCell", bundle: nil)
collectionView?.registerNib(scrollSelectionCellNib, forCellWithReuseIdentifier: scrollSelectionCellIdentifier)
let physiologicalHeaderViewNib = UINib(nibName: "PhysiologicalHeaderView", bundle: nil)
collectionView?.registerNib(physiologicalHeaderViewNib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "sectionHeaderView")
}
internal func isSleepCellAtIndexPath(indexPath: NSIndexPath) -> Bool {
return indexPath.section == 0 && indexPath.row == 0
}
// MARK: - UICollectionView DataSource & Delegate
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return model.sections.count
}
override public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return model.numberOfItemsInSection(section)
}
override public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let item = model.itemAtIndexPath(indexPath)
if isSleepCellAtIndexPath(indexPath) {
// it is sleep cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(scrollSelectionCellIdentifier, forIndexPath: indexPath) as! ScrollSelectionViewCell
cell.minValue = 3
cell.maxValue = 12
cell.titleLbl.text = item.name
cell.smallDescriptionLbl.text = item.unitsTitle
cell.pickerShown = editMode
cell.titleLbl.font = AdditionalInfoFont
cell.smallDescriptionLbl.font = AdditionalInfoUnitsFont
cell.valueLbl.font = AdditionalInfoFont
if let value = item.intValue() where value > 0 {
cell.setSelectedValue(value)
} else {
let defaultValue = 8
self.model.setNewValueForItem(atIndexPath: indexPath, newValue: defaultValue)
cell.setSelectedValue(defaultValue)
}
cell.changesHandler = { (cell: UICollectionViewCell, newValue: AnyObject?) -> () in
if let indexPath = self.collectionView!.indexPathForCell(cell) {
self.model.setNewValueForItem(atIndexPath: indexPath, newValue: newValue)
}
}
return cell
}
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(titledInputCellIdentifier, forIndexPath: indexPath) as! TitledInputCollectionViewCell
cell.titleLbl.text = item.name
if let strValue = item.stringValue() {
cell.inputTxtField.text = strValue
//cell.inputTxtField.font = ScreenManager.appFontOfSize(15.0)
}
else {
cell.inputTxtField.text = nil
//cell.inputTxtField.font = ScreenManager.appFontOfSize(13.0)
}
cell.smallDescriptionLbl.text = item.unitsTitle
let attr = [NSForegroundColorAttributeName : unselectedTextColor, NSFontAttributeName: AdditionalInfoFont]
cell.inputTxtField.attributedPlaceholder = NSAttributedString(string: item.title, attributes: attr)
var keypadType = UIKeyboardType.Default
if item.dataType == .Int {
keypadType = UIKeyboardType.NumberPad
}
else if item.dataType == .Decimal {
keypadType = UIKeyboardType.DecimalPad
}
cell.inputTxtField.keyboardType = keypadType
cell.titleLbl.textColor = selectedTextColor
cell.inputTxtField.textColor = selectedTextColor
cell.smallDescriptionLbl.textColor = unselectedTextColor
cell.titleLbl.font = AdditionalInfoFont
cell.inputTxtField.font = AdditionalInfoFont
cell.smallDescriptionLbl.font = AdditionalInfoUnitsFont
cell.titleLbl.adjustsFontSizeToFitWidth = true
cell.titleLbl.numberOfLines = 0
cell.inputTxtField.adjustsFontSizeToFitWidth = true
cell.inputTxtField.minimumFontSize = 10.0
cell.smallDescriptionLbl.adjustsFontSizeToFitWidth = true
cell.smallDescriptionLbl.numberOfLines = 1
cell.changesHandler = { (cell: UICollectionViewCell, newValue: AnyObject?) -> () in
if let indexPath = self.collectionView!.indexPathForCell(cell) {
self.model.setNewValueForItem(atIndexPath: indexPath, newValue: newValue)
}
}
cell.userInteractionEnabled = editMode
return cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "sectionHeaderView", forIndexPath: indexPath) as! HeaderView
headerView.titleLbl.text = model.sectionTitleAtIndexPath(indexPath)
return headerView
}
return UICollectionReusableView()
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSizeMake(CGRectGetWidth(collectionView.frame), 50)
}
// MARK: - Cells sizes
private let cellHeight: CGFloat = 60
private let cellHeightHight: CGFloat = 110
private func defaultCellSize() -> CGSize {
let size = CGSizeMake(self.collectionView!.bounds.width, cellHeight)
return size
}
private func intPickerCellSize() -> CGSize {
let size = CGSizeMake(self.collectionView!.bounds.width, editMode ? cellHeightHight : cellHeight)
return size
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return isSleepCellAtIndexPath(indexPath) ? intPickerCellSize() : defaultCellSize()
}
func reset() {
self.model.updateValues()
}
}
| b660c1d665380c35cbdfe33347302105 | 39.808989 | 171 | 0.702919 | false | false | false | false |
raulriera/ForecastView | refs/heads/master | ForecastView/ForecastView/ForecastCollectionViewCell.swift | mit | 1 | //
// ForecastCollectionViewCell.swift
// WeatherView
//
// Created by Raul Riera on 28/07/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
class ForecastCollectionViewCell: UICollectionViewCell, ForecastViewDisplayable {
var forecast: Forecast? {
didSet {
didUpdateForecast()
}
}
lazy private var dayLabel: UILabel = {
let label = UILabel(frame: CGRectZero)
label.font = .systemFontOfSize(12)
label.textColor = .whiteColor()
label.textAlignment = .Center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy private var conditionsView: ConditionsView = {
let font: UIFont
if #available(iOS 8.2, *) {
font = UIFont.systemFontOfSize(20, weight: UIFontWeightThin)
} else {
font = UIFont.systemFontOfSize(20)
}
let view = ConditionsView(frame: CGRectZero, font: font)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
static var identifier: String {
return "ForecastCollectionViewCell"
}
internal func configureSubviews() {
contentView.addSubview(dayLabel)
contentView.addSubview(conditionsView)
let views = ["dayLabel": dayLabel, "conditionsView": conditionsView]
let horizontalConstraintsConditionsView = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[conditionsView]-0-|", options: [], metrics: nil, views: views)
let horizontalConstraintsDayLabel = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[dayLabel]-0-|", options: [], metrics: nil, views: views)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[dayLabel]-0-[conditionsView]-0-|", options: [], metrics: nil, views: views)
NSLayoutConstraint.activateConstraints(horizontalConstraintsConditionsView + horizontalConstraintsDayLabel + verticalConstraints)
}
internal func didUpdateForecast() {
configureSubviews()
if let forecast = forecast {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE"
dayLabel.text = dateFormatter.stringFromDate(forecast.date)
conditionsView.forecast = forecast
}
}
} | 2eb4a2573cc4cb53021b5dd2371a9b2f | 32.986111 | 167 | 0.645544 | false | false | false | false |
ayushgoel/SAHistoryNavigationViewController | refs/heads/master | SAHistoryNavigationViewControllerSample/SAHistoryNavigationViewControllerSample/TimelineView/TimelineViewController.swift | mit | 1 | //
// TimelineViewController.swift
// SAHistoryNavigationViewControllerSample
//
// Created by 鈴木大貴 on 2015/04/01.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
class TimelineViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
private let kCellIdentifier = "Cell"
private var contents: [TimelineContent] = [
TimelineContent(username: "Alex", text: "This is SAHistoryNavigationViewController."),
TimelineContent(username: "Brian", text: "It has history jump function."),
TimelineContent(username: "Cassy", text: "If you want to launch history viewer,"),
TimelineContent(username: "Dave", text: "please tap longer \"<Back\" of Navigation Bar."),
TimelineContent(username: "Elithabeth", text: "You can see ViewController history"),
TimelineContent(username: "Alex", text: "as horizonal scroll view."),
TimelineContent(username: "Brian", text: "If you select one of history,"),
TimelineContent(username: "Cassy", text: "go back to that ViewController."),
TimelineContent(username: "Dave", text: "Thanks for trying this sample."),
TimelineContent(username: "Elithabeth", text: "by skz-atmosphere")
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
title = "Timeline"
let nib = UINib(nibName: "TimelineViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: kCellIdentifier)
tableView.separatorInset = UIEdgeInsetsZero
tableView.layoutMargins = UIEdgeInsetsZero
tableView.dataSource = self
tableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
struct TimelineContent {
var username: String
var text: String
}
@IBAction func segueBack(segue: UIStoryboardSegue) {}
}
extension TimelineViewController: UITableViewDataSource {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier)!
if let cell = cell as? TimelineViewCell {
let num = indexPath.row % 5 + 1
if let image = UIImage(named: "icon_\(num)") {
cell.setIconImage(image)
}
let content = contents[indexPath.row]
cell.setUsername(content.username)
cell.setMainText(content.text)
}
cell.layoutMargins = UIEdgeInsetsZero
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contents.count
}
}
extension TimelineViewController: UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let viewController = storyboard.instantiateViewControllerWithIdentifier("DetailViewController") as? DetailViewController {
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? TimelineViewCell {
viewController.iconImage = cell.iconImageView?.image
}
let content = contents[indexPath.row]
viewController.username = content.username
viewController.text = content.text
navigationController?.pushViewController(viewController, animated: true)
}
}
} | 9206a0a15b9d6c1ac255e91bb3e344c6 | 37.529412 | 133 | 0.664546 | false | false | false | false |
DominikButz/DYAlertController | refs/heads/master | DYAlertControllerExample3/Pods/DYAlertController/DYAlertController/DYAlertController.swift | mit | 2 | //
// DYActionViewController.swift
//
//
// Created by Dominik Butz on 22/02/16.
//
//
import UIKit
public class DYAlertAction {
public enum ActionStyle {
case Default
case Destructive
case Disabled
}
var title:String
var iconImage: UIImage?
var selected:Bool
var handler: ((DYAlertAction) -> Void)?
var style:ActionStyle = .Default
public init(title:String, style:ActionStyle?, iconImage:UIImage?, setSelected:Bool, handler: ((DYAlertAction) -> Void)?) {
if let _ = style {
self.style = style!
}
self.selected = setSelected
self.title = title
self.iconImage = iconImage
self.handler = handler
}
}
public class TapView: UIView {
var touchHandler: ((UIView) -> Void)?
override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
touchHandler?(self)
}
}
public class DYAlertController: UIViewController, UITableViewDelegate, UITableViewDataSource {
public enum Style {
case Alert
case ActionSheet
}
public enum EffectViewMode {
case blur, dim
}
@IBOutlet weak var backgroundView: TapView!
@IBOutlet weak var backgroundViewTopConstraint: NSLayoutConstraint!
@IBOutlet weak var backgroundViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var contentViewCenterYtoSuperviewConstraint: NSLayoutConstraint!
@IBOutlet weak var contentViewWidthConstraint: NSLayoutConstraint!
var contentViewCustomWidth:CGFloat?
@IBOutlet weak var mainView: UIView!
var animationEffectView:UIView?
public var textField:UITextField?
@IBOutlet weak var titleView: UIView!
@IBOutlet weak var titleViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var titleImageView: UIImageView?
@IBOutlet weak var titleLabel: UILabel?
@IBOutlet weak var messageLabel: UILabel?
@IBOutlet public weak var okButton: UIButton?
@IBOutlet weak var okButtonHeightConstraint: NSLayoutConstraint?
@IBOutlet weak var okButtonToMainViewConstraint: NSLayoutConstraint?
public var handleOKAction: (()->Void)?
@IBOutlet weak var buttonSeparatorLine: UIView?
@IBOutlet weak var cancelButton: UIButton!
// @IBOutlet weak var cancelButtonTrailingConstraint: NSLayoutConstraint!
@IBOutlet weak var cancelButtonToMainViewConstraint: NSLayoutConstraint!
@IBOutlet weak var cancelButtonHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var cancelButtonWidthConstraint: NSLayoutConstraint!
public var handleCancelAction: (()->Void)?
@IBOutlet weak var topSeparatorLine: UIView!
@IBOutlet weak var bottomSeparatorLine: UIView!
@IBOutlet weak var cancelButtonToOKButtonConstraint: NSLayoutConstraint?
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint!
var alertActions:[DYAlertAction] = []
var titleText:String?
var messageText:String?
var titleIconImage:UIImage?
var cancelButtonTitle:String?
var okButtonTitle:String?
var shouldAllowMultipleSelection = false
var style:Style = .Alert
var backgroundEffectViewMode:EffectViewMode = .dim
var isPresenting = false
public var titleViewSettings = DYAlertSettings.TitleViewSettings()
public var buttonSettings = DYAlertSettings.ButtonSettings()
public var textFieldSettings = DYAlertSettings.TextFieldSettings()
public var actionCellSettings = DYAlertSettings.ActionCellSettings()
public var contentViewSettings = DYAlertSettings.ContentViewSettings()
public var effectViewSettings = DYAlertSettings.EffectViewSettings()
// add title, title icon?, cancel button title, ok button title?
public convenience init() {
self.init(nibName: "DYAlertController", bundle: NSBundle(forClass: DYAlertController.self))
}
public convenience init(style:Style, title:String?, titleIconImage:UIImage?, message:String?, cancelButtonTitle:String, okButtonTitle:String?, multipleSelection:Bool, customFrameWidth:CGFloat?, backgroundEffect: EffectViewMode) {
self.init()
self.style = style
self.titleText = title
self.messageText = message
self.titleIconImage = titleIconImage
self.cancelButtonTitle = cancelButtonTitle
self.okButtonTitle = okButtonTitle
if let _ = self.okButtonTitle {
self.shouldAllowMultipleSelection = multipleSelection
}
self.contentViewCustomWidth = customFrameWidth
self.backgroundEffectViewMode = backgroundEffect
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
//super.init()
modalPresentationStyle = .Custom
modalTransitionStyle = .CrossDissolve
transitioningDelegate = self
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func viewDidLoad() {
super.viewDidLoad()
layoutSubviews()
}
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if titleText != nil && titleIconImage == nil && messageText == nil {
let titleLabelYPositionConstraint = NSLayoutConstraint(item: titleView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: titleLabel, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0)
titleView.addConstraint(titleLabelYPositionConstraint)
}
backgroundView.touchHandler = { _ in
self.dismissViewControllerAnimated(true, completion: nil)
}
self.setCellSelectedIfNeeded()
}
override public func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if let _ = textField {
textField!.becomeFirstResponder()
}
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if self.animationEffectView == nil {
return
}
if self.style == .ActionSheet { // change layout constraint for Action Sheet: move content view down to bottom
self.contentViewCenterYtoSuperviewConstraint.constant = self.contentView.superview!.frame.size.height / 2.0 - self.contentView.frame.size.height / 2.0 - 10.0
}
if let _ = textField {
// correct textfield positioning
textField!.frame = CGRectMake(20.0, 5.0, tableView.tableHeaderView!.bounds.size.width - 40.0, 30.0)
}
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: UI Setup
private func layoutSubviews() {
contentView.autoresizingMask = .FlexibleHeight
contentView.layer.cornerRadius = contentViewSettings.cornerRadius
contentView.autoresizesSubviews = true
if let _ = contentViewCustomWidth {
contentViewWidthConstraint.constant = contentViewCustomWidth!
}
mainView.clipsToBounds = true
mainView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
mainView.backgroundColor = contentViewSettings.mainViewBackgroundColor
if style == .ActionSheet {
bottomSeparatorLine.removeFromSuperview()
}
tableView.delegate = self
tableView.dataSource = self
tableView.registerNib(UINib(nibName: "DYActionCell", bundle: NSBundle(forClass: DYActionCell.self)), forCellReuseIdentifier: "DYActionCell")
if let _ = okButtonTitle {
tableView.allowsMultipleSelection = self.shouldAllowMultipleSelection
}
tableView.separatorStyle = .SingleLineEtched
tableView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
layoutTitleView()
layoutButtons()
if let _ = textField {
layoutTextField()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
}
}
private func adjustTableViewHeight() {
var height:CGFloat = 0.0
if let _ = textField {
height = height + textField!.frame.size.height
if alertActions.count == 0 {
height = height + 30.0
} else {
height = height + 20.0
}
}
if alertActions.count > 0 {
height = height + self.getCellHeight() * CGFloat(alertActions.count)
}
self.tableViewHeightConstraint.constant = height
}
private func layoutTitleView() {
titleView.backgroundColor = titleViewSettings.backgroundColor
var viewElementsCounter = 0
var titleViewHeight:CGFloat = 5.0
if let _ = titleIconImage {
titleImageView?.image = self.titleIconImage
titleImageView?.contentMode = .ScaleAspectFit
titleViewHeight += titleImageView!.frame.size.height
viewElementsCounter += 1
} else {
titleImageView?.removeFromSuperview()
}
if let _ = titleText {
titleLabel!.text = titleText
titleLabel!.textColor = self.titleViewSettings.titleTextColor
titleLabel!.font = self.titleViewSettings.titleTextFont
titleLabel!.sizeToFit()
titleViewHeight += titleLabel!.frame.size.height
viewElementsCounter += 1
} else {
titleLabel?.removeFromSuperview()
}
if let _ = messageText {
messageLabel!.text = messageText!
messageLabel!.textColor = self.titleViewSettings.messageTextColor
messageLabel!.font = self.titleViewSettings.messageTextFont
messageLabel!.sizeToFit()
titleViewHeight += messageLabel!.frame.size.height
viewElementsCounter += 1
} else {
messageLabel?.removeFromSuperview()
}
titleViewHeightConstraint.constant = titleViewHeight
if viewElementsCounter == 0 {
topSeparatorLine.removeFromSuperview()
}
else if viewElementsCounter == 1 {
titleViewHeightConstraint.constant += 10.0
}
}
private func layoutButtons() {
okButton?.backgroundColor = buttonSettings.okButtonBackgroundColor
cancelButton.backgroundColor = buttonSettings.cancelButtonBackgroundColor
cancelButton.setTitleColor(buttonSettings.cancelButtonTintColor, forState: UIControlState.Normal)
if let _ = okButtonTitle {
okButton!.setTitle(okButtonTitle!, forState: UIControlState.Normal)
okButton!.setTitleColor(buttonSettings.okButtonTintColor, forState: UIControlState.Normal)
if style == .Alert {
cancelButtonWidthConstraint.constant = contentViewWidthConstraint.constant / 2.0
} else { // Action Sheet
cancelButtonWidthConstraint.constant = contentViewWidthConstraint.constant / 2.0 - 8.0
}
} else {
// no ok title, no button!
okButton?.removeFromSuperview()
buttonSeparatorLine?.removeFromSuperview()
cancelButtonWidthConstraint.constant = contentViewWidthConstraint.constant
}
cancelButton.setTitle(cancelButtonTitle, forState: UIControlState.Normal)
if self.style == .Alert {
cancelButtonToMainViewConstraint.constant = 0
okButtonToMainViewConstraint?.constant = 0
contentView.backgroundColor = UIColor.whiteColor()
contentView.clipsToBounds = true
} else {
// Action sheet!
okButton?.layer.cornerRadius = buttonSettings.cornerRadius
okButtonHeightConstraint?.constant = 30.0
cancelButton.layer.cornerRadius = buttonSettings.cornerRadius
cancelButtonHeightConstraint.constant = 30.0
mainView.layer.cornerRadius = contentViewSettings.cornerRadius
buttonSeparatorLine?.removeFromSuperview()
}
print("cancel button width: \(cancelButton.frame.size.width), ok button width:\(okButton?.frame.size.width)")
}
private func layoutTextField() {
self.topSeparatorLine.removeFromSuperview()
let rect = CGRectMake(00.0, 0.0, tableView.frame.size.width, 40.0)
let headerView = UIView(frame: rect)
print("table view width: \(tableView.frame.size.width)")
print("header view width less 40: \( headerView.bounds.size.width - 40.0)")
let textFieldFrame = CGRectMake(20.0, 5.0, headerView.bounds.size.width - 40.0, 30.0)
textField!.frame = textFieldFrame
textField!.borderStyle = .RoundedRect
textField!.font = textFieldSettings.textFont
textField!.backgroundColor = textFieldSettings.backgroundColor
textField!.textColor = textFieldSettings.textColor
headerView.addSubview(textField!)
tableView.tableHeaderView = headerView
}
public func addAction(action: DYAlertAction) {
self.alertActions.append(action)
}
public func addTextField(text: String?) {
if style == .ActionSheet {
assertionFailure("Action sheet does not support text fields. Change style to .alert instead!")
}
guard let _ = textField else {
textField = UITextField()
textField!.text = text
return
}
}
//MARK: Table view data source and delegate
private func setCellSelectedIfNeeded() {
if let _ = self.okButtonTitle{
var indexCounter = -1
for actionItem in alertActions {
indexCounter += 1
if actionItem.selected == true {
tableView.selectRowAtIndexPath(NSIndexPath(forRow: indexCounter, inSection: 0), animated: false, scrollPosition: UITableViewScrollPosition.None)
}
}
}
}
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
self.adjustTableViewHeight()
return alertActions.count
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("cell for row at... called")
let cell = tableView.dequeueReusableCellWithIdentifier("DYActionCell") as?
DYActionCell
let actionItem = alertActions[indexPath.row]
cell!.configureCell(actionItem, hasAccessoryView: (okButtonTitle != nil), settings:actionCellSettings)
return cell!
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("did select...")
let action = alertActions[indexPath.row]
if self.okButtonTitle == nil {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
self.dismissViewControllerAnimated(true, completion: nil)
action.selected = true
} else {
action.selected = action.selected ? false : true
if action.selected {
tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: .Middle)
} else {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
if action.handler != nil {
action.handler!(action)
}
}
public func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
print("did deselect row... called")
if let _ = self.okButtonTitle {
let action = alertActions[indexPath.row]
print("deselecting... seting action.selected to false")
action.selected = false
if action.handler != nil {
action.handler!(action)
}
}
}
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
print("height for row at.. called")
return self.getCellHeight()
}
private func getCellHeight()->CGFloat {
let heightLabelFrame = CGRectMake(0, 0, 100.0, 44.0)
let heightLabel = UILabel(frame: heightLabelFrame)
heightLabel.font = actionCellSettings.actionCellFont
heightLabel.text = "Height"
heightLabel.sizeToFit()
return max(30.0, heightLabel.frame.size.height * 1.8)
}
//MARK: Actions
@IBAction func cancelButtonTapped(sender: UIButton) {
// print("cancel button tapped")
handleCancelAction?()
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func okButtonTapped(sender: UIButton) {
handleOKAction?()
dismissViewControllerAnimated(true, completion: nil)
}
// func didTapBackground(recognizer: UITapGestureRecognizer) {
//
// dismissViewControllerAnimated(true, completion: nil)
// }
//MARK: notifications
func keyboardWillShow(notification: NSNotification) {
let info = notification.userInfo!
let value: AnyObject = info[UIKeyboardFrameEndUserInfoKey]!
let rawFrame = value.CGRectValue
let keyboardFrame = view.convertRect(rawFrame, fromView: nil)
self.contentViewCenterYtoSuperviewConstraint.constant = self.contentView.superview!.frame.size.height / 2.0 - self.contentView.frame.size.height / 2.0 - keyboardFrame.size.height - 10.0
UIView.animateWithDuration(0.25) { () -> Void in
self.backgroundView.layoutIfNeeded()
}
}
}
//MARK: Extensions - Animated Transitioning
extension DYAlertController: UIViewControllerTransitioningDelegate {
public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.isPresenting = true
return self
}
public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.isPresenting = false
return self
}
}
extension DYAlertController: UIViewControllerAnimatedTransitioning {
private func animationDuration()->NSTimeInterval {
return 0.5
}
private func createDimView(frame: CGRect) -> UIView {
let dimView = UIView(frame: frame)
dimView.backgroundColor = self.effectViewSettings.dimViewColor
dimView.alpha = 0
dimView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
return dimView
}
private func createBlurView(frame:CGRect)->UIView{
let blurEffect = UIBlurEffect(style: self.effectViewSettings.blurViewStyle)
let blurredView = UIVisualEffectView(effect: blurEffect)
blurredView.frame = frame
blurredView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
blurredView.alpha = 0
return blurredView
}
private func getbackgroundEffectView(frame:CGRect)->UIView {
var effectView:UIView = UIView()
if backgroundEffectViewMode == .dim {
effectView = self.createDimView(frame)
}
if backgroundEffectViewMode == .blur {
effectView = self.createBlurView(frame)
}
return effectView
}
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return self.animationDuration()
}
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
guard let container = transitionContext.containerView() else {
return transitionContext.completeTransition(false)
}
guard let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) else {
return transitionContext.completeTransition(false)
}
guard let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) else {
return transitionContext.completeTransition(false)
}
if isPresenting == true {
if style == .Alert {
self.presentAlertAnimation(container, fromView: fromVC.view, toView: toVC.view, completion: { (_) -> Void in
transitionContext.completeTransition(true)
})
} else {
//style Action Sheet
self.presentActionSheetAnimation(container, fromView: fromVC.view, toView: toVC.view, completion: { (_) -> Void in
transitionContext.completeTransition(true)
})
}
} else {
if style == .Alert {
self.dismissAlertAnimation(fromVC.view, completion: { (_) -> Void in
transitionContext.completeTransition(true)
})
}
else {
// Action Sheet
self.dismissActionSheetAnimation(container, toView: toVC.view, completion: { (_) -> Void in
transitionContext.completeTransition(true)
})
}
}
}
private func presentAlertAnimation(container: UIView, fromView: UIView, toView:UIView, completion: (Bool)->Void) {
let dimView = self.getbackgroundEffectView(container.bounds)
container.addSubview(dimView)
toView.frame = container.bounds
// starting transform:
toView.transform = CGAffineTransformConcat(fromView.transform, CGAffineTransformMakeScale(0.0, 1.0))
// this works, too
//CGAffineTransformConcat(CGAffineTransformMakeScale(1.0, 1.0), CGAffineTransformMakeScale(0.0, 1.0))
dimView.addSubview(toView)
self.animationEffectView = dimView
//transitionCoverView = coverView
UIView.animateWithDuration(animationDuration(), animations: { () -> Void in
toView.transform = fromView.transform // set to original transform !
dimView.alpha = 1.0
}, completion: completion)
}
private func dismissAlertAnimation(fromView:UIView, completion: (Bool)->Void) {
UIView.animateWithDuration(animationDuration(), animations: { () -> Void in
fromView.transform = CGAffineTransformMakeScale(0.01, 1.0)
self.animationEffectView?.alpha = 0
self.animationEffectView = nil
}, completion: completion)
}
private func presentActionSheetAnimation(container: UIView, fromView:UIView, toView:UIView, completion: (Bool)->Void) {
let effectView = self.getbackgroundEffectView(container.bounds)
container.addSubview(effectView)
toView.frame = container.bounds
effectView.addSubview(toView)
backgroundViewBottomConstraint.constant = -toView.bounds.height
backgroundViewTopConstraint.constant = toView.bounds.height
backgroundView.layoutIfNeeded()
self.backgroundViewTopConstraint.constant = 0.0
self.backgroundViewBottomConstraint.constant = 0.0
self.animationEffectView = effectView
UIView.animateWithDuration(animationDuration(), delay: 0.0, options: .CurveEaseIn, animations: { () -> Void in
self.backgroundView.layoutIfNeeded()
effectView.alpha = 1.0
}, completion: completion)
}
private func dismissActionSheetAnimation(container:UIView, toView: UIView, completion: (Bool)->Void) {
backgroundViewTopConstraint.constant = toView.bounds.height
backgroundViewBottomConstraint.constant = -toView.bounds.height
UIView.animateWithDuration(animationDuration(), animations: { () -> Void in
self.backgroundView.layoutIfNeeded()
self.animationEffectView?.alpha = 0
self.animationEffectView = nil
}, completion: completion)
}
}
| 062cedabb49ed9be5990d05480ef668b | 29.266896 | 246 | 0.613254 | false | false | false | false |
NestedWorld/NestedWorld-iOS | refs/heads/develop | nestedworld/nestedworld/RegisterViewController.swift | mit | 1 | //
// RegisterViewController.swift
// nestedworld
//
// Created by Jean-Antoine Dupont on 17/02/2016.
// Copyright © 2016 NestedWorld. All rights reserved.
//
import UIKit
class RegisterViewController: UIViewController
{
@IBOutlet weak var infoLabel: UILabel!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var nicknameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var confirmPasswordField: UITextField!
private let apiRequestManager = APIRequestManager()
// MARK: Override functions
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
self.infoLabel.text = ""
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Action functions
@IBAction func registerButton(sender: AnyObject)
{
if (self.checkParams() == true) {
let button = sender as! UIButton
button.enabled = false
self.infoLabel.text = ""
self.apiRequestManager.getUserManager().getAuthenticationManager()
.register(self.emailField.text!, nickname: self.nicknameField.text!, password: self.passwordField.text!,
success: { (response) -> Void in
self.infoLabel.text = "You are now registered"
}, failure: { (error, response) -> Void in
self.infoLabel.text = self.printError(error, response: response)
button.enabled = true
})
}
}
// MARK: Private functions
private func checkParams() -> Bool
{
if (self.emailField == nil || self.emailField.text?.isEmpty == true) {
self.infoLabel.text = "Email field is missing"
return false
}
if (self.nicknameField == nil || self.nicknameField.text?.isEmpty == true) {
self.infoLabel.text = "Nickname field is missing"
return false
}
if (self.nicknameField.text?.characters.count < 3) {
self.infoLabel.text = "Nickname need more characters"
return false
}
if (self.passwordField == nil || self.passwordField.text?.isEmpty == true) {
self.infoLabel.text = "Password field is missing"
return false
}
if (self.passwordField.text != self.confirmPasswordField.text) {
self.infoLabel.text = "Password field and its confirmation field are not the same"
return false
}
return true
}
private func printError(error: NSError?, response: AnyObject?) -> String
{
return "Error connection"
}
}
| 17ea93a8dea233b74196ff5d0963927e | 29.122449 | 120 | 0.580962 | false | false | false | false |
liuweicode/LinkimFoundation | refs/heads/master | Example/LinkimFoundation/Foundation/UI/Component/TextField/PhoneTextField.swift | mit | 1 | //
// PhoneTextField.swift
// LinkimFoundation
//
// Created by 刘伟 on 16/7/8.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import UIKit
import LinkimFoundation
let kPhoneNumLen = 11 //用户手机号长度限制
class PhoneTextField: BaseTextField,UITextFieldDelegate,BaseTextFieldDelegate {
func initTextData() {
self.placeholder = "请输入手机号"
self.keyboardType = .NumberPad
self.font = UIFont.systemFontOfSize(16)
self.clearButtonMode = .WhileEditing
self.translatesAutoresizingMaskIntoConstraints = false
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
let components = newString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
var decimalString = components.joinWithSeparator("") as String
let length = decimalString.length
if length <= 3 {
textField.text = decimalString
}else if length > 3 && length <= 7 {
decimalString.insert(" ", atIndex: decimalString.startIndex.advancedBy(3))
textField.text = decimalString
}else if length <= kPhoneNumLen {
decimalString.insert(" ", atIndex: decimalString.startIndex.advancedBy(3))
decimalString.insert(" ", atIndex: decimalString.startIndex.advancedBy(8))
textField.text = decimalString
}
self.delegate?.textField!(textField, shouldChangeCharactersInRange: range, replacementString: string)
return false
}
func textFieldDidEndEditing(textField: UITextField) {
self.delegate?.textFieldDidEndEditing?(textField)
}
}
| 8f862d6d5d4ca99f925fb25da82ba5a8 | 36.77551 | 132 | 0.690978 | false | false | false | false |
coderMONSTER/ioscelebrity | refs/heads/master | YStar/YStar/General/Base/BaseTableViewController.swift | mit | 1 | //
// BaseTableViewController.swift
// viossvc
//
// Created by yaowang on 2016/10/27.
// Copyright © 2016年 ywwlcom.yundian. All rights reserved.
//
import Foundation
import SVProgressHUD
class BaseTableViewController: UITableViewController , TableViewHelperProtocol {
var tableViewHelper:TableViewHelper = TableViewHelper();
override func viewDidLoad() {
super.viewDidLoad();
// if tableView.tableFooterView == nil {
// tableView.tableFooterView = UIView(frame:CGRect(x: 0,y: 0,width: 0,height: 0.5));
// }
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
MobClick.beginLogPageView(NSStringFromClass(self.classForCoder))
AppDataHelper.instance().userBalance()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
SVProgressHUD.dismiss()
MobClick.endLogPageView(NSStringFromClass(self.classForCoder))
}
//MARK:TableViewHelperProtocol
func isCacheCellHeight() -> Bool {
return false;
}
func isCalculateCellHeight() ->Bool {
return isCacheCellHeight();
}
func isSections() ->Bool {
return false;
}
func tableView(_ tableView:UITableView ,cellIdentifierForRowAtIndexPath indexPath: IndexPath) -> String? {
return tableViewHelper.tableView(tableView, cellIdentifierForRowAtIndexPath: indexPath, controller: self);
}
func tableView(_ tableView:UITableView ,cellDataForRowAtIndexPath indexPath: IndexPath) -> AnyObject? {
return nil;
}
//MARK: -UITableViewDelegate
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell? = super.tableView(tableView,cellForRowAt:indexPath);
if cell == nil {
cell = tableViewHelper.tableView(tableView, cellForRowAtIndexPath: indexPath, controller: self);
}
return cell!;
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
tableViewHelper.tableView(tableView, willDisplayCell: cell, forRowAtIndexPath: indexPath, controller: self);
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if( isCalculateCellHeight() ) {
let cellHeight:CGFloat = tableViewHelper.tableView(tableView, heightForRowAtIndexPath: indexPath, controller: self);
if( cellHeight != CGFloat.greatestFiniteMagnitude ) {
return cellHeight;
}
}
return super.tableView(tableView, heightForRowAt: indexPath);
}
}
class BaseRefreshTableViewController :BaseTableViewController {
override func viewDidLoad() {
super.viewDidLoad();
self.setupRefreshControl();
}
internal func completeBlockFunc()->CompleteBlock {
return { [weak self] (obj) in
self?.didRequestComplete(obj)
}
}
internal func didRequestComplete(_ data:AnyObject?) {
endRefreshing()
self.tableView.reloadData()
}
override func didRequestError(_ error:NSError) {
self.endRefreshing()
super.didRequestError(error)
}
deinit {
performSelectorRemoveRefreshControl();
}
}
class BaseListTableViewController :BaseRefreshTableViewController {
internal var dataSource:Array<AnyObject>?;
override func didRequestComplete(_ data: AnyObject?) {
dataSource = data as? Array<AnyObject>;
super.didRequestComplete(dataSource as AnyObject?);
}
//MARK: -UITableViewDelegate
override func numberOfSections(in tableView: UITableView) -> Int {
var count:Int = dataSource != nil ? 1 : 0;
if isSections() && count != 0 {
count = dataSource!.count;
}
return count;
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var datas:Array<AnyObject>? = dataSource;
if dataSource != nil && isSections() {
datas = dataSource![section] as? Array<AnyObject>;
}
return datas == nil ? 0 : datas!.count;
}
//MARK:TableViewHelperProtocol
override func tableView(_ tableView:UITableView ,cellDataForRowAtIndexPath indexPath: IndexPath) -> AnyObject? {
var datas:Array<AnyObject>? = dataSource;
if dataSource != nil && isSections() {
datas = dataSource![indexPath.section] as? Array<AnyObject>;
}
return (datas != nil && datas!.count > indexPath.row ) ? datas![indexPath.row] : nil;
}
}
class BasePageListTableViewController :BaseListTableViewController {
override func viewDidLoad() {
super.viewDidLoad();
setupLoadMore();
}
override func didRequestComplete(_ data: AnyObject?) {
tableViewHelper.didRequestComplete(&self.dataSource,
pageDatas: data as? Array<AnyObject>, controller: self);
super.didRequestComplete(self.dataSource as AnyObject?);
}
override func didRequestError(_ error:NSError) {
if (!(self.pageIndex == 1) ) {
self.errorLoadMore()
}
self.setIsLoadData(true)
super.didRequestError(error)
}
deinit {
removeLoadMore();
}
}
| 180e17c772b0c82c161595706ed1f899 | 29.911602 | 128 | 0.637355 | false | false | false | false |
hanwanjie853710069/Easy-living | refs/heads/master | 易持家/Class/CoreData/CoreDataAddAndDelete.swift | apache-2.0 | 1 | //
// CoreDataAddAndDelete.swift
// 易持家
//
// Created by 王木木 on 16/5/24.
// Copyright © 2016年 王木木. All rights reserved.
//
import Foundation
/// 向数据表Information添加数据
func insertInterformationData(zsMoney: String ,
zsNote: String ,
zwMoney: String ,
zwNote: String ,
wsMoney: String ,
wsNote: String ,
zjeMoney:String ,
xfMonery:String ,
syMonery:String ,
xfTime: String){
let inf = NSEntityDescription.insertNewObjectForEntityForName("Information",
inManagedObjectContext: managedObjectContext) as! Information
inf.creatTime = String(NSDate().timeIntervalSince1970)
inf.ids = 1
inf.syMoney = syMonery
inf.wsMoney = wsMoney
inf.wsNote = wsNote
inf.xfAllMoney = xfMonery
inf.xfTime = xfTime
inf.zjeMoney = zjeMoney
inf.zsMoney = zsMoney
inf.zsNote = zsNote
inf.zwMoney = zwMoney
inf.zwNote = zwNote
inf.weather = queryDataWeather()
let weatherr = queryDataWeatherObject()
inf.weathers = NSSet(object: weatherr)
//保存
do {
try managedObjectContext.save()
print("保存成功!")
let alertController = UIAlertController(title: "数据保存成功",
message: nil, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "确定", style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
UIApplication.sharedApplication().keyWindow?.rootViewController!.presentViewController(alertController, animated: true, completion: nil)
} catch {
fatalError("不能保存:\(error)")
}
}
/// 向数据表Information查询数据
func queryDataInformation() ->[Information]{
var arrayData = [Information]()
//查询操作
do {
let fetchedObjects:[AnyObject]? = try managedObjectContext.executeFetchRequest(getNSFetchRequest())
//遍历查询的结果
for info:Information in fetchedObjects as! [Information]{
arrayData.insert(info, atIndex: 0)
// let temp = info.weathers?.allObjects as! [Weather]
// for aa in temp {
// print(aa.baiDay)
// }
}
}
catch {
fatalError("查询失败:\(error)")
}
return arrayData
}
/// 获取NSFetchRequest对象
func getNSFetchRequest() ->NSFetchRequest{
//声明数据的请求
let fetchRequest:NSFetchRequest = NSFetchRequest()
//声明一个实体结构
let entity:NSEntityDescription? = NSEntityDescription.entityForName("Information",
inManagedObjectContext: managedObjectContext)
//设置数据请求的实体结构
fetchRequest.entity = entity
return fetchRequest
}
/// 向数据表Information删除数据 yes 成功 no失败
func deleteInformationData(reattTimeIds: String) ->Bool{
//查询操作
do {
let fetchedObjects:[AnyObject]? = try managedObjectContext.executeFetchRequest(getNSFetchRequest())
//遍历查询的结果
for info:Information in fetchedObjects as! [Information]{
if info.creatTime == reattTimeIds {
//删除对象
managedObjectContext.deleteObject(info)
return true
}
}
}
catch {
fatalError("删除失败:\(error)")
}
do{
//重新保存-更新到数据库
try managedObjectContext.save()
}catch {
fatalError("重新保存-更新到数据库:\(error)")
}
return false
}
/// 向数据表Information修改数据
func modifyTheInterformationData(zsMoney: String ,
zsNote: String ,
zwMoney: String ,
zwNote: String ,
wsMoney: String ,
wsNote: String ,
zjeMoney:String ,
xfMonery:String ,
syMonery:String ,
xfTime: String ,
cjTime: String ) ->Bool{
//查询操作
do {
//查询条件
let predicate = NSPredicate(format: "creatTime= '\(cjTime)' ")
let fetchRequest = getNSFetchRequest()
fetchRequest.predicate = predicate
let fetchedObjects:[AnyObject]? = try
managedObjectContext.executeFetchRequest(fetchRequest)
//遍历查询的结果
for inf:Information in fetchedObjects as! [Information]{
if inf.creatTime == cjTime {
inf.syMoney = syMonery
inf.wsMoney = wsMoney
inf.wsNote = wsNote
inf.xfAllMoney = xfMonery
inf.zjeMoney = zjeMoney
inf.zsMoney = zsMoney
inf.zsNote = zsNote
inf.zwMoney = zwMoney
inf.zwNote = zwNote
}
}
}
catch {
fatalError("修改失败:\(error)")
}
do{
//重新保存-更新到数据库
try managedObjectContext.save()
return true
}catch {
fatalError("重新保存-更新到数据库:\(error)")
}
return false
}
/// 向Weather表插入数据
func insertWeatherData(baiDay : String ,
city : String ,
clothes : String ,
maxTemperature: String ,
minTemperature: String ,
wanDay : String){
deleteWeatherInformation()
let weather = NSEntityDescription.insertNewObjectForEntityForName("Weather",
inManagedObjectContext: managedObjectContext) as! Weather
weather.baiDay = baiDay
weather.city = city
weather.clothes = clothes
weather.maxTemperature = maxTemperature
weather.minTemperature = minTemperature
weather.wanDay = wanDay
do{
try managedObjectContext.save()
}catch{
print("\(error)")
}
}
/// 删除Weather表中的所有数据
func deleteWeatherInformation(){
//声明数据的请求
let fetchRequest:NSFetchRequest = NSFetchRequest()
//声明一个实体结构
let entity:NSEntityDescription? = NSEntityDescription.entityForName("Weather",
inManagedObjectContext: managedObjectContext)
//设置数据请求的实体结构
fetchRequest.entity = entity
let fetchedObjects:[AnyObject]? = try? managedObjectContext.executeFetchRequest(fetchRequest)
//遍历查询的结果
for inf:Weather in fetchedObjects as! [Weather]{
//删除对象
managedObjectContext.deleteObject(inf)
}
Appdel.saveContext()
}
/// 向Weather表中查询数据 返回天气信息
func queryDataWeather() ->String{
//声明数据的请求
let fetchRequest:NSFetchRequest = NSFetchRequest()
//声明一个实体结构
let entity:NSEntityDescription? = NSEntityDescription.entityForName("Weather",
inManagedObjectContext: managedObjectContext)
//设置数据请求的实体结构
fetchRequest.entity = entity
let fetchedObjects:[AnyObject]? = try? managedObjectContext.executeFetchRequest(fetchRequest)
//遍历查询的结果
for inf:Weather in fetchedObjects as! [Weather]{
let weather = inf.city!
+ " 白天:" + inf.baiDay!
+ " 夜晚:" + inf.wanDay!
+ " 最高温度:"
+ inf.maxTemperature!
+ " 最低温度:"
+ inf.minTemperature!
+ " 穿衣推荐:" + inf.clothes!
return weather
}
return "没有获取到天气数据"
}
/// 向Weather表中查询数据 返回 Weather对象
func queryDataWeatherObject() ->Weather{
let weather = NSEntityDescription.insertNewObjectForEntityForName("Weather", inManagedObjectContext: managedObjectContext) as! Weather
//声明数据的请求
let fetchRequest:NSFetchRequest = NSFetchRequest()
//声明一个实体结构
let entity:NSEntityDescription? = NSEntityDescription.entityForName("Weather",
inManagedObjectContext: managedObjectContext)
//设置数据请求的实体结构
fetchRequest.entity = entity
let fetchedObjects:[AnyObject]? = try? managedObjectContext.executeFetchRequest(fetchRequest)
//遍历查询的结果
for inf:Weather in fetchedObjects as! [Weather]{
weather.baiDay = inf.baiDay
weather.city = inf.city
weather.clothes = inf.clothes
weather.maxTemperature = inf.maxTemperature
weather.minTemperature = inf.minTemperature
weather.wanDay = inf.wanDay
return weather
}
return Weather()
}
/// 存储获取到的天气地址
func insertAddressData(array:NSMutableArray){
for dict in array {
let city = dict["city"] as! String
let cnty = dict["cnty"] as! String
let id = dict["id"] as! String
let lat = dict["lat"] as! String
let lon = dict["lon"] as! String
let prov = dict["prov"] as! String
let address = NSEntityDescription.insertNewObjectForEntityForName("Address",
inManagedObjectContext: managedObjectContext) as! Address
address.city = city
address.cnty = cnty
address.id = id
address.lat = lat
address.lon = lon
address.prov = prov
}
do{
try managedObjectContext.save()
}catch{
print("\(error)")
}
}
/// 获取本地存储的天气地址
func queryDataAddress() ->NSMutableArray{
let array: NSMutableArray = []
//声明数据的请求
let fetchRequest:NSFetchRequest = NSFetchRequest()
//声明一个实体结构
let entity:NSEntityDescription? = NSEntityDescription.entityForName("Address",
inManagedObjectContext: managedObjectContext)
//设置数据请求的实体结构
fetchRequest.entity = entity
let fetchedObjects:[AnyObject]? = try? managedObjectContext.executeFetchRequest(fetchRequest)
//遍历查询的结果
for inf in fetchedObjects!{
array.addObject(inf)
}
return array
}
/// 向User表插入数据 用户表
func insertUserData(age : String ,
backgroundUrl : String ,
heardUrl : String ,
userName : String ,
nickName : String ,
passWord : String ,
sex : String ) -> Bool{
let user = NSEntityDescription.insertNewObjectForEntityForName("User",
inManagedObjectContext: managedObjectContext) as! User
user.age = age
user.backgroundUrl = backgroundUrl
user.heardUrl = heardUrl
user.userName = userName
user.nickName = nickName
user.passWord = passWord
user.sex = sex
//保存
do {
try managedObjectContext.save()
return true
} catch {
return false
}
}
/// 向User表中查询数据 返回用户信息
func queryDataUser() ->User{
//声明数据的请求
let fetchRequest:NSFetchRequest = NSFetchRequest()
//声明一个实体结构
let entity:NSEntityDescription? = NSEntityDescription.entityForName("User",
inManagedObjectContext: managedObjectContext)
//设置数据请求的实体结构
fetchRequest.entity = entity
let fetchedObjects:[AnyObject]? = try? managedObjectContext.executeFetchRequest(fetchRequest)
//遍历查询的结果
for inf:User in fetchedObjects as! [User]{
print(inf.age)
print(inf.userName)
print(inf.passWord)
print(inf.nickName)
print(inf.heardUrl)
return inf
}
insertUserData("",
backgroundUrl: "",
heardUrl: "",
userName: "",
nickName: "",
passWord: "",
sex: "")
return queryDataUser()
}
/// 删除User表中的所有数据
func deleteUserInformation(){
//声明数据的请求
let fetchRequest:NSFetchRequest = NSFetchRequest()
//声明一个实体结构
let entity:NSEntityDescription? = NSEntityDescription.entityForName("User",
inManagedObjectContext: managedObjectContext)
//设置数据请求的实体结构
fetchRequest.entity = entity
let fetchedObjects:[AnyObject]? = try? managedObjectContext.executeFetchRequest(fetchRequest)
//遍历查询的结果
for inf:User in fetchedObjects as! [User]{
//删除对象
managedObjectContext.deleteObject(inf)
}
Appdel.saveContext()
}
/// 向数据表User修改数据
func modifyTheUserData(modifyName: String, modifyValue: String ) ->Bool{
//声明数据的请求
let fetchRequest:NSFetchRequest = NSFetchRequest()
//声明一个实体结构
let entity:NSEntityDescription? = NSEntityDescription.entityForName("User",
inManagedObjectContext: managedObjectContext)
//设置数据请求的实体结构
fetchRequest.entity = entity
//查询操作
do {
let fetchedObjects:[AnyObject]? = try managedObjectContext.executeFetchRequest(fetchRequest)
//遍历查询的结果
for user:User in fetchedObjects as! [User]{
switch modifyName {
case "age":
user.age = modifyValue
print("年龄")
case "backgroundUrl":
user.backgroundUrl = modifyValue
print("背景url")
case "heardUrl":
user.heardUrl = modifyValue
print("头像url")
case "userName":
user.userName = modifyValue
print("用户名字")
case "nickName":
user.nickName = modifyValue
print("昵称")
case "passWord":
user.passWord = modifyValue
print("密码")
default:
user.sex = modifyValue
print("性别修改")
}
}
}
catch {fatalError("修改失败:\(error)")}
do{
//重新保存-更新到数据库
try managedObjectContext.save()
return true
}catch {fatalError("重新保存-更新到数据库:\(error)")}
return false
} | ed587f53728d03eddc62bfb346930be0 | 22.843427 | 144 | 0.489375 | false | false | false | false |
Lisergishnu/TetraVex | refs/heads/develop | TetraVex/TVGameViewController.swift | gpl-3.0 | 1 | //
// BoardViewController.swift
// TetraVex
//
// Created by Marco Benzi Tobar on 17-06-16.
// Modified by Alessandro Vinciguerra
//
// Copyright © 2016 Marco Benzi Tobar
//
// Copyright © 2017 Arc676/Alessandro Vinciguerra
//
// 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 (version 3)
//
// 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 Cocoa
import TetraVexKit
import GameplayKit
class TVGameViewController: NSViewController
{
var solvedBoard : [[TVPieceModel]]? = nil
@IBOutlet weak var boardAreaBox: TVBoardView!
@IBOutlet weak var templatePieceView: TVPieceView!
var currentPiecesOnBoard : [TVPieceView] = []
var boardModel: TVBoardModel?
var delegate : AppDelegate?
@IBOutlet weak var boardHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var boardWidthConstraint: NSLayoutConstraint!
//timing
var timer: Timer?
var secondsPassed: Int = 0
@IBOutlet weak var timerLabel: NSTextField!
//scores
var scores: TVHighScores?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
delegate = NSApplication.shared.delegate as? AppDelegate
scores = TVHighScores.read()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func newBoard(_ width: Int, height: Int) {
boardModel = TVBoardModel(width: width, height: height)
// Refresh autolayout
let pw = templatePieceView.frame.width
let ph = templatePieceView.frame.height
boardWidthConstraint.constant = pw*CGFloat(width)
boardHeightConstraint.constant = ph*CGFloat(height)
/* Generate and shuffle new pieces */
/* Also delete previous pieces */
for pv in currentPiecesOnBoard {
pv.removeFromSuperview()
}
if ((solvedBoard) != nil) {
visiblePieces = [TVPieceView]()
for i in 0..<width {
for j in 0..<height {
let nfr = templatePieceView.frame.offsetBy(dx: pw*CGFloat(i), dy: -ph*CGFloat(j))
let pv : TVPieceView = TVPieceView(frame: nfr)
pv.autoresizingMask = [NSView.AutoresizingMask.maxXMargin, NSView.AutoresizingMask.minYMargin]
currentPiecesOnBoard.append(pv)
pv.pieceModel = solvedBoard![i][j]
pv.delegate = self
self.view.addSubview(pv)
visiblePieces?.append(pv)
}
}
}
//start timing the game
if timer != nil {
timer?.invalidate()
timer = nil
}
secondsPassed = 0
timer = Timer.scheduledTimer(
timeInterval: 1,
target: self,
selector: #selector(tick),
userInfo: nil,
repeats: true)
}
func removeFromBoard(piece p:TVPieceView) -> Bool {
if boardModel!.removePieceFromBoard(p.pieceModel!) {
p.pieceModel!.isOnBoard = false
return true
}
return false
}
func checkPiece(with pv:TVPieceView,at dropOffPosition:NSPoint) {
/* Determine the position of view inside the grid */
if boardAreaBox.frame.contains(dropOffPosition) {
let i : Int = Int((dropOffPosition.x - boardAreaBox.frame.origin.x) / pv.frame.width)
let j : Int = Int((dropOffPosition.y - boardAreaBox.frame.origin.y) / pv.frame.height)
if boardModel!.addPieceToBoard(pv.pieceModel!, x: i, y: j) {
pv.frame.origin.x = CGFloat(i)*pv.frame.width + boardAreaBox.frame.origin.x
pv.frame.origin.y = CGFloat(j)*pv.frame.height + boardAreaBox.frame.origin.y
pv.pieceModel?.isOnBoard = true
if boardModel!.isCompleted() {
timer?.invalidate()
timer = nil
let size = "\(boardModel!.boardWidth)x\(boardModel!.boardHeight)"
scores?.scores?[size]?[NSDate()] = secondsPassed
scores?.save()
}
} else {
let randomSource = GKARC4RandomSource()
var newOrigin = templatePieceView.frame.origin
newOrigin.x += CGFloat(Int.random(0...100,randomSource: randomSource))
newOrigin.y -= CGFloat(Int.random(0...100,randomSource: randomSource))
pv.animator().setFrameOrigin(newOrigin)
}
}
}
//MARK: - Timing
@objc func tick() {
secondsPassed += 1
timerLabel.stringValue = TVHighScores.timeToString(secondsPassed)
}
// MARK: Changing the piece text style
var visiblePieces : [TVPieceView]?
func setTextStyle(to style:TVPieceModel.TextStyle) {
guard let pieces = visiblePieces else {
return
}
textStyle(for: pieces, style)
}
func textStyle(for pieces:[TVPieceView],_ style: TVPieceModel.TextStyle) {
for piece in pieces {
guard var model = piece.pieceModel else {
continue
}
model.textStyle = style
piece.pieceModel = model
piece.needsDisplay = true
}
}
}
extension TVGameViewController : TVPieceViewDelegate {
func wasLiftedFromBoard(piece: TVPieceView) {
removeFromBoard(piece: piece)
guard let layer = piece.layer else {
return
}
layer.shadowColor = NSColor.black.cgColor
layer.shadowOpacity = 0.75
layer.shadowOffset = CGSize(width: 5,height: 10)
layer.shadowRadius = 10
}
func wasDropped(piece: TVPieceView, at: NSPoint) {
checkPiece(with: piece, at: at)
guard let layer = piece.layer else {
return
}
layer.shadowOpacity = 0.0
}
}
| b0dd23a052b15b643a60378d7a20dcc5 | 29.757895 | 104 | 0.663587 | false | false | false | false |
fdierick/SimpleRESTServer | refs/heads/master | development.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import Cocoa
var str = "Hello, playground"
func readJSON (filepath:String ) -> String? {
// Check if file exists at given file path
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = dir.stringByAppendingPathComponent(filepath);
print(path)
do {
let text = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
let validJson = validateJSON(text as String)
if (validJson) {
// All good, return JSON as String
return text as String
} else {
// File contains no valid JSON
return nil
}
}
catch {
// File cannot be read
return nil
}
} else {
// File does not exist
return nil
}
}
func validateJSON(jsonString: String) -> Bool {
let jsonData: NSData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
do {
// Use _ because we don't actually care about the result, just that it's valid JSON
_ = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! [String:AnyObject]
return true
} catch {
// Invalid JSON
return false
}
}
let good = readJSON("sub/file.json")
let bad = readJSON("badfile.json")
NSFileManager.defaultManager().currentDirectoryPath
| 26a73a1b130419d8ea111f2e144aa329 | 22.911765 | 157 | 0.582411 | false | false | false | false |
tutsplus/CoreDataSwift-RelationshipsMoreFetching | refs/heads/master | Core Data/AppDelegate.swift | bsd-2-clause | 1 | //
// AppDelegate.swift
// Core Data
//
// Created by Bart Jacobs on 17/10/15.
// Copyright © 2015 Envato Tuts+. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
/*
// Create Person
let entityPerson = NSEntityDescription.entityForName("Person", inManagedObjectContext: self.managedObjectContext)
let newPerson = NSManagedObject(entity: entityPerson!, insertIntoManagedObjectContext: self.managedObjectContext)
// Populate Person
newPerson.setValue("Bart", forKey: "first")
newPerson.setValue("Jacobs", forKey: "last")
newPerson.setValue(44, forKey: "age")
// Create Address
let entityAddress = NSEntityDescription.entityForName("Address", inManagedObjectContext: self.managedObjectContext)
let newAddress = NSManagedObject(entity: entityAddress!, insertIntoManagedObjectContext: self.managedObjectContext)
// Populate Address
newAddress.setValue("Main Street", forKey: "street")
newAddress.setValue("Boston", forKey: "city")
// Add Address to Person
newPerson.setValue(NSSet(object: newAddress), forKey: "addresses")
do {
try newPerson.managedObjectContext?.save()
} catch {
let saveError = error as NSError
print(saveError)
}
// Create Address
let otherAddress = NSManagedObject(entity: entityAddress!, insertIntoManagedObjectContext: self.managedObjectContext)
// Set First and Last Name
otherAddress.setValue("5th Avenue", forKey:"street")
otherAddress.setValue("New York", forKey:"city")
// Add Address to Person
let addresses = newPerson.mutableSetValueForKey("addresses")
addresses.addObject(otherAddress)
// Delete Relationship
newPerson.setValue(nil, forKey:"addresses")
// Create Another Person
let anotherPerson = NSManagedObject(entity: entityPerson!, insertIntoManagedObjectContext: self.managedObjectContext)
// Set First and Last Name
anotherPerson.setValue("Jane", forKey: "first")
anotherPerson.setValue("Doe", forKey: "last")
anotherPerson.setValue(42, forKey: "age")
// Create Relationship
newPerson.setValue(anotherPerson, forKey: "spouse")
// Create a Child Person
let newChildPerson = NSManagedObject(entity: entityPerson!, insertIntoManagedObjectContext: self.managedObjectContext)
// Set First and Last Name
newChildPerson.setValue("Jim", forKey: "first")
newChildPerson.setValue("Doe", forKey: "last")
newChildPerson.setValue(21, forKey: "age")
// Create Relationship
let children = newPerson.mutableSetValueForKey("children")
children.addObject(newChildPerson)
// Create Another Child Person
let anotherChildPerson = NSManagedObject(entity: entityPerson!, insertIntoManagedObjectContext: self.managedObjectContext)
// Set First and Last Name
anotherChildPerson.setValue("Lucy", forKey: "first")
anotherChildPerson.setValue("Doe", forKey: "last")
anotherChildPerson.setValue(19, forKey: "age")
// Create Relationship
anotherChildPerson.setValue(newPerson, forKey: "father")
do {
try self.managedObjectContext.save()
} catch {
let saveError = error as NSError
print(saveError)
}
*/
/*
// Create Fetch Request
let fetchRequest = NSFetchRequest(entityName: "Person")
// Add Sort Descriptor
let sortDescriptor1 = NSSortDescriptor(key: "last", ascending: true)
let sortDescriptor2 = NSSortDescriptor(key: "age", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor1, sortDescriptor2]
// Execute Fetch Request
do {
let result = try self.managedObjectContext.executeFetchRequest(fetchRequest)
for managedObject in result {
if let first = managedObject.valueForKey("first"), last = managedObject.valueForKey("last"), age = managedObject.valueForKey("age") {
print("\(first) \(last) (\(age))")
}
}
} catch {
let fetchError = error as NSError
print(fetchError)
}
*/
// Fetching
let fetchRequest = NSFetchRequest(entityName: "Person")
// Create Predicate
// let predicate = NSPredicate(format: "%K == %@", "last", "Doe")
// let predicate = NSPredicate(format: "%K >= %i", "age", 30)
// let predicate = NSPredicate(format: "%K CONTAINS[c] %@", "first", "j")
// let predicate = NSPredicate(format: "%K CONTAINS[c] %@ AND %K < %i", "first", "j", "age", 30)
let predicate = NSPredicate(format: "%K == %@", "father.first", "Bart")
fetchRequest.predicate = predicate
// Add Sort Descriptor
let sortDescriptor1 = NSSortDescriptor(key: "last", ascending: true)
let sortDescriptor2 = NSSortDescriptor(key: "age", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor1, sortDescriptor2]
// Execute Fetch Request
do {
let result = try self.managedObjectContext.executeFetchRequest(fetchRequest)
for managedObject in result {
if let first = managedObject.valueForKey("first"), last = managedObject.valueForKey("last"), age = managedObject.valueForKey("age") {
print("\(first) \(last) (\(age))")
}
}
} catch {
let fetchError = error as NSError
print(fetchError)
}
return true
}
func applicationWillResignActive(application: UIApplication) {}
func applicationDidEnterBackground(application: UIApplication) {}
func applicationWillEnterForeground(application: UIApplication) {}
func applicationDidBecomeActive(application: UIApplication) {}
func applicationWillTerminate(application: UIApplication) {
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.tutsplus.Core_Data" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Core_Data", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 3d82a090e9b139417ce7eb6f581565bb | 42.957806 | 291 | 0.648205 | false | false | false | false |
liuweihaocool/iOS_06_liuwei | refs/heads/master | 新浪微博_swift/新浪微博_swift/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// 新浪微博_swift
//
// Created by liuwei on 15/11/22.
// Copyright © 2015年 liuwei. All rights reserved.
//
//LWCollectionViewController(collectionViewLayout: UICollectionViewLayout() 流水布局
//外部提供流水布局 但是不太好 流水布局需要设置参数 让调用的人来设置参数 封装的不是特别好
import UIKit
@UIApplicationMain //https://git.oschina.net/czbkiosweibo/GZWeibo666.git git 教师案例fd
class AppDelegate: UIResponder, UIApplicationDelegate {
// 声明变量window
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
appsetup()
window = UIWindow(frame: UIScreen.mainScreen().bounds)//创建window
window?.backgroundColor = UIColor.whiteColor()
/// 创建 tabBarVC 控制器
// let tabBarVC = LWFeatureController()
/// 设置 tarBarVC 为根控制器
window?.rootViewController = defaultController()
window?.makeKeyAndVisible()//设置keywindow和显示
return true
}
// MARK: - 判断进入哪个控制器
private func defaultController() -> UIViewController {
// 用户是否登录,加载到账户就表示登录
if !LWUserAccount.userLogin {
return LWMainTarbarController()
}
//
return isNewFeature() ? LWFeatureController() : LWWelcomeController()
}
private func switchRootViewController(isMain: Bool) {
print(isMain)
window?.rootViewController = isMain ? LWMainTarbarController() : LWWelcomeController()
}
class func switchRootViewController(isMain: Bool) {
(UIApplication.sharedApplication().delegate as! AppDelegate).switchRootViewController(isMain)
}
///判断是否是新版本
private func isNewFeature() -> Bool{
//获取当前版本
let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)!
// 获取上次版本(从偏好设置)
let sandboxVersionKey = "sandboxVersionKey"
//上次的版本号
let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
// 保存当前版本
NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandboxVersionKey)
NSUserDefaults.standardUserDefaults().synchronize()
return currentVersion != sandboxVersion
}
func appsetup() {
let bar = UINavigationBar.appearance()
bar.tintColor = UIColor.orangeColor()
}
func applicationWillResignActive(application: UIApplication) {
}
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:.
}
}
| 1ef423bfc2e90cde12b2fe6947d0c596 | 37.851064 | 218 | 0.700986 | false | false | false | false |
donbytyqi/WatchBox | refs/heads/master | WatchBox Reborn/Extensions.swift | mit | 1 | //
// Extensions.swift
// WatchBox Reborn
//
// Created by Don Bytyqi on 5/2/17.
// Copyright © 2017 Don Bytyqi. All rights reserved.
//
import UIKit
let imageCache = NSCache<AnyObject, AnyObject>()
class CoverImage: UIImageView {
var coverImageURL: String?
func downloadImageFrom(urlString: String) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
coverImageURL = urlString
guard let url = URL(string: urlString) else { return }
image = UIImage(named: "nocover")
if let isCachedImage = imageCache.object(forKey: urlString as AnyObject) {
self.image = isCachedImage as? UIImage
UIApplication.shared.isNetworkActivityIndicatorVisible = false
return
}
UIApplication.shared.isNetworkActivityIndicatorVisible = true
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
}
DispatchQueue.main.async {
guard let imageData = data else { return }
let cachedImage = UIImage(data: imageData)
if self.coverImageURL == urlString {
self.image = cachedImage
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
UIApplication.shared.isNetworkActivityIndicatorVisible = true
imageCache.setObject(cachedImage!, forKey: urlString as AnyObject)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}.resume()
}
}
public func addBlur(toView: UIView) {
let blurEffect = UIBlurEffect(style: .dark)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = toView.bounds
blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
toView.addSubview(blurView)
}
extension UIView
{
func searchVisualEffectsSubview() -> UIVisualEffectView?
{
if let visualEffectView = self as? UIVisualEffectView
{
return visualEffectView
}
else
{
for subview in subviews
{
if let found = subview.searchVisualEffectsSubview()
{
return found
}
}
}
return nil
}
}
extension UISearchBar {
func cancelButton(_ isEnabled: Bool) {
for subview in self.subviews {
for button in subview.subviews {
if button.isKind(of: UIButton.self) {
let cancelButton = button as! UIButton
cancelButton.isEnabled = isEnabled
}
}
}
}
}
class Alert: NSObject {
func show(title: String, message: String, controller: UIViewController) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
controller.present(alert, animated: true, completion: nil)
}
}
| c39b48045afa9251222def13f933e502 | 28.432432 | 93 | 0.573003 | false | false | false | false |
RoverPlatform/rover-ios | refs/heads/master | Sources/Foundation/Attributes.swift | apache-2.0 | 1 | //
// Attributes.swift
// RoverFoundation
//
// Created by Sean Rucker on 2018-07-24.
// Copyright © 2018 Rover Labs Inc. All rights reserved.
//
import Foundation
import os
// We have a strong guarantee that this will complete. Very deterministic, done in static context at startup, so silence the force try warning.
// swiftlint:disable:next force_try
private let roverKeyRegex = try! NSRegularExpression(pattern: "^[a-zA-Z_][a-zA-Z_0-9]*$")
/// Wraps a [String: Any], a dictionary of values, but enables use of both NSCoding and Codable. Enforces the Rover limitations on allowed types and nesting thereof (not readily capturable in the Swift type system) at runtime.
///
/// Note that there are several constraints here, enforced by the Rover cloud API itself, not expressed in the Swift type. Namely, arrays may not be present within dictionaries or other arrays. These are checked at runtime.
///
/// Thus:
///
/// * `String`
/// * `Int`
/// * `Double`
/// * `Bool`
/// * `[String]`
/// * `[Int]`
/// * `[Double]`
/// * `[Bool]`
/// * `[String: Any]` (where Any may be any of these given types)
public class Attributes: NSObject, NSCoding, Codable, RawRepresentable, ExpressibleByDictionaryLiteral {
public var rawValue: [String: Any]
public required init(rawValue: [String: Any]) {
// transform nested dictionaries to Attributes, if needed.
let nestedDictionariesTransformedToAttributes = rawValue.mapValues { value -> Any in
if let dictionary = value as? [String: Any] {
return Attributes(rawValue: dictionary) as Any? ?? Attributes()
} else {
return value
}
}
self.rawValue = Attributes.validateDictionary(nestedDictionariesTransformedToAttributes)
}
public required init(dictionaryLiteral elements: (String, Any)...) {
let dictionary = elements.reduce(into: [String: Any]()) { result, element in
let (key, value) = element
result[key] = value
}
// transform nested dictionaries to Attributes, if needed.
let nestedDictionariesTransformedToAttributes = dictionary.mapValues { value -> Any in
if let dictionary = value as? [String: Any] {
return Attributes(rawValue: dictionary) as Any? ?? Attributes()
} else {
return value
}
}
self.rawValue = Attributes.validateDictionary(nestedDictionariesTransformedToAttributes)
}
//
// MARK: Subscript
//
public subscript(index: String) -> Any? {
get {
return rawValue[index]
}
set(newValue) {
rawValue[index] = newValue
}
}
//
// MARK: NSCoding
//
public func encode(with aCoder: NSCoder) {
var boolToBoolean: ((Any) -> Any)
boolToBoolean = { anyValue in
switch anyValue {
case let value as Bool:
return BooleanValue(value)
case let value as [Bool]:
return value.map { BooleanValue($0) }
default:
return anyValue
}
}
let nsDictionary = self.rawValue.mapValues(boolToBoolean) as Dictionary
aCoder.encode(nsDictionary)
}
public required init?(coder aDecoder: NSCoder) {
guard let nsDictionary = aDecoder.decodeObject() as? NSDictionary else {
return nil
}
let dictionary = nsDictionary.dictionaryWithValues(forKeys: nsDictionary.allKeys as! [String])
func transformDictionary(dictionary: [String: Any]) -> [String: Any] {
return dictionary.reduce(into: [String: Any]()) { result, element in
switch element.value {
// handle our custom boxed Boolean value type:
case let value as BooleanValue:
result[element.key] = value.value
case let array as [BooleanValue]:
result[element.key] = array.map { $0.value }
case let attributesDictionary as Attributes:
// if a nested dictionary is already attributes, then pass it through.
result[element.key] = attributesDictionary
default:
result[element.key] = element.value
}
}
}
self.rawValue = Attributes.validateDictionary(transformDictionary(dictionary: dictionary))
super.init()
}
fileprivate static func validateDictionary(_ dictionary: [String: Any]) -> [String: Any] {
var transformed: [String: Any] = [:]
// This is a set of mappings of types, which makes for a long closure body, so silence the closure length warning.
// swiftlint:disable:next closure_body_length
dictionary.forEach { key, value in
let swiftRange = Range(uncheckedBounds: (key.startIndex, key.endIndex))
let nsRange = NSRange(swiftRange, in: key)
if roverKeyRegex.matches(in: key, range: nsRange).isEmpty {
assertionFailureEmitter("Invalid key: \(key)")
return
}
if let nestedDictionary = value as? Attributes {
transformed[key] = nestedDictionary
return
}
if !(
value is Double ||
value is Int ||
value is String ||
value is Bool ||
value is [Double] ||
value is [Int] ||
value is [String] ||
value is [Bool]
) {
let valueType = type(of: value)
assertionFailureEmitter("Invalid value for key \(key) with unsupported type: \(String(describing: valueType))")
return
}
transformed[key] = value
}
return transformed
}
//
// MARK: Codable
//
/// This implementation of CodingKey allows for handling data without strongly and statically typed keys with Codable.
struct DynamicCodingKeys: CodingKey {
var stringValue: String
init(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int? {
return nil
}
init?(intValue: Int) {
return nil
}
}
public required init(from decoder: Decoder) throws {
func fromKeyedDecoder(_ container: KeyedDecodingContainer<Attributes.DynamicCodingKeys>) throws -> Attributes {
var assembledHash = [String: Any]()
// This is a set of mappings of types, which makes for a long closure body, so silence the closure length warning.
// swiftlint:disable:next closure_body_length
try container.allKeys.forEach { key in
let keyString = key.stringValue
// primitive values:
if let value = try? container.decode(Bool.self, forKey: key) {
assembledHash[keyString] = value
return
}
if let value = try? container.decode(Int.self, forKey: key) {
assembledHash[keyString] = value
return
}
if let value = try? container.decode(String.self, forKey: key) {
assembledHash[keyString] = value
return
}
// now try probing for an embedded dict.
if let dictionary = try? container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: key) {
assembledHash[keyString] = try fromKeyedDecoder(dictionary)
return
}
// we also support arrays of primitive values:
if let array = try? container.decode([String].self, forKey: key) {
assembledHash[keyString] = array
return
}
if let array = try? container.decode([Bool].self, forKey: key) {
assembledHash[keyString] = array
return
}
if let array = try? container.decode([Int].self, forKey: key) {
assembledHash[keyString] = array
return
}
if let array = try? container.decode([Double].self, forKey: key) {
assembledHash[keyString] = array
return
}
throw DecodingError.dataCorruptedError(forKey: key, in: container, debugDescription: "Expected one of Int, String, Double, Bool, or an Array thereof.")
}
return Attributes(rawValue: assembledHash)
}
let container = try decoder.container(keyedBy: DynamicCodingKeys.self)
self.rawValue = try fromKeyedDecoder(container).rawValue
}
public func encode(to encoder: Encoder) throws {
/// nested function for recursing through the dictionary and populating the Encoder with it, doing the necessary type coercions on the way.
func encodeToContainer(dictionary: [String: Any], container: inout KeyedEncodingContainer<Attributes.DynamicCodingKeys>) throws {
// This is a set of mappings of types, which makes for a long closure body, so silence the function length warning.
// swiftlint:disable:next closure_body_length
try dictionary.forEach { codingKey, value in
let key = DynamicCodingKeys(stringValue: codingKey)
switch value {
case let value as Int:
try container.encode(value, forKey: key)
case let value as Bool:
try container.encode(value, forKey: key)
case let value as String:
try container.encode(value, forKey: key)
case let value as Double:
try container.encode(value, forKey: key)
case let value as [Int]:
try container.encode(value, forKey: key)
case let value as [Bool]:
try container.encode(value, forKey: key)
case let value as [Double]:
try container.encode(value, forKey: key)
case let value as [String]:
try container.encode(value, forKey: key)
case let value as Attributes:
var nestedContainer = container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: key)
try encodeToContainer(dictionary: value.rawValue, container: &nestedContainer)
default:
let context = EncodingError.Context(codingPath: container.codingPath, debugDescription: "Unexpected attribute value type. Expected one of Int, String, Double, Boolean, or an array thereof, or a dictionary of all of the above including arrays. Got \(type(of: value))")
throw EncodingError.invalidValue(value, context)
}
}
}
var container = encoder.container(keyedBy: DynamicCodingKeys.self)
try encodeToContainer(dictionary: self.rawValue, container: &container)
}
override init() {
rawValue = [:]
super.init()
}
static func wasAssertionThrown(operation: () -> Void) -> Bool {
let originalEmitter = assertionFailureEmitter
var thrown = false
assertionFailureEmitter = { message in
os_log("Attributes assertion thrown: %s", message)
thrown = true
}
operation()
assertionFailureEmitter = originalEmitter
return thrown
}
/// Needed so tests can override the method of emitting assertion failures.
private static var assertionFailureEmitter: (String) -> Void = { message in
assertionFailure(message)
}
}
class BooleanValue: NSObject, NSCoding {
var value: Bool
func encode(with aCoder: NSCoder) {
aCoder.encode(value, forKey: "value")
}
required init?(coder aDecoder: NSCoder) {
value = aDecoder.decodeBool(forKey: "value")
}
init(_ value: Bool) {
self.value = value
}
}
| 6d9534271c6bbd1db0bbc41133bc2205 | 38.611285 | 287 | 0.565211 | false | false | false | false |
ben-ng/swift | refs/heads/master | validation-test/compiler_crashers_fixed/01085-swift-declcontext-lookupqualified.swift | apache-2.0 | 1 | // 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
struct B<T : A> {
func f<g>() -> (g, g -> g) -> g {
d j d.i = {
}
{
g) {
h }
}
protocol f {
}
class d: f{ class func i {}
struct d<f : e,e where g.h == f.h> {
}
}
protocol a {
typeal= D>(e: A.B) {
}
}
}
override func d() -> String {
func}
func b((Any, c))(Any, AnyObject
func g<T where T.E == F>(f: B<T>) {
}
struct c<S: Sequence, T where Optional<T> == S.Iterator.Element>
| 2dd071fba0233f3d34c22df166a3ae76 | 22.454545 | 79 | 0.643411 | false | false | false | false |
JohnSansoucie/MyProject2 | refs/heads/master | BlueCap/Utils/UITableViewControllerExtensions.swift | mit | 1 | //
// UITableViewControllerExtensions.swift
// BlueCap
//
// Created by Troy Stribling on 9/27/14.
// Copyright (c) 2014 gnos.us. All rights reserved.
//
import UIKit
extension UITableViewController {
func updateWhenActive() {
if UIApplication.sharedApplication().applicationState == .Active {
self.tableView.reloadData()
}
}
func styleNavigationBar() {
let font = UIFont(name:"Thonburi", size:20.0)
var titleAttributes : [NSObject:AnyObject]
if var defaultTitleAttributes = UINavigationBar.appearance().titleTextAttributes {
titleAttributes = defaultTitleAttributes
} else {
titleAttributes = [NSObject:AnyObject]()
}
titleAttributes[NSFontAttributeName] = font
self.navigationController?.navigationBar.titleTextAttributes = titleAttributes
}
func styleUIBarButton(button:UIBarButtonItem) {
let font = UIFont(name:"Thonburi", size:16.0)
var titleAttributes : [NSObject:AnyObject]
if var defaultitleAttributes = button.titleTextAttributesForState(UIControlState.Normal) {
titleAttributes = defaultitleAttributes
} else {
titleAttributes = [NSObject:AnyObject]()
}
titleAttributes[NSFontAttributeName] = font
button.setTitleTextAttributes(titleAttributes, forState:UIControlState.Normal)
}
}
| c5b87972693d430f24810fdc89651fb5 | 32.904762 | 98 | 0.672051 | false | false | false | false |
narner/AudioKit | refs/heads/master | AudioKit/Common/Nodes/Generators/Physical Models/Plucked String/AKPluckedString.swift | mit | 1 | //
// AKPluckedString.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// Karplus-Strong plucked string instrument.
///
open class AKPluckedString: AKNode, AKToggleable, AKComponent {
public typealias AKAudioUnitType = AKPluckedStringAudioUnit
/// Four letter unique description of the node
public static let ComponentDescription = AudioComponentDescription(generator: "pluk")
// MARK: - Properties
private var internalAU: AKAudioUnitType?
private var token: AUParameterObserverToken?
fileprivate var frequencyParameter: AUParameter?
fileprivate var amplitudeParameter: AUParameter?
fileprivate var lowestFrequency: Double
/// Ramp Time represents the speed at which parameters are allowed to change
@objc open dynamic var rampTime: Double = AKSettings.rampTime {
willSet {
internalAU?.rampTime = newValue
}
}
/// Variable frequency. Values less than the initial frequency will be doubled until it is greater than that.
@objc open dynamic var frequency: Double = 110 {
willSet {
if frequency != newValue {
if let existingToken = token {
frequencyParameter?.setValue(Float(newValue), originator: existingToken)
}
}
}
}
/// Amplitude
@objc open dynamic var amplitude: Double = 0.5 {
willSet {
if amplitude != newValue {
if let existingToken = token {
amplitudeParameter?.setValue(Float(newValue), originator: existingToken)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
@objc open dynamic var isStarted: Bool {
return internalAU?.isPlaying() ?? false
}
// MARK: - Initialization
/// Initialize the pluck with defaults
override convenience init() {
self.init(frequency: 110)
}
/// Initialize this pluck node
///
/// - Parameters:
/// - frequency: Variable frequency. Values less than the initial frequency will be
/// doubled until it is greater than that.
/// - amplitude: Amplitude
/// - lowestFrequency: This frequency is used to allocate all the buffers needed for the delay.
/// This should be the lowest frequency you plan on using.
///
@objc public init(
frequency: Double = 440,
amplitude: Double = 0.5,
lowestFrequency: Double = 110) {
self.frequency = frequency
self.amplitude = amplitude
self.lowestFrequency = lowestFrequency
_Self.register()
super.init()
AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in
self?.avAudioNode = avAudioUnit
self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType
}
guard let tree = internalAU?.parameterTree else {
AKLog("Parameter Tree Failed")
return
}
frequencyParameter = tree["frequency"]
amplitudeParameter = tree["amplitude"]
token = tree.token(byAddingParameterObserver: { [weak self] _, _ in
guard let _ = self else {
AKLog("Unable to create strong reference to self")
return
} // Replace _ with strongSelf if needed
DispatchQueue.main.async {
// This node does not change its own values so we won't add any
// value observing, but if you need to, this is where that goes.
}
})
internalAU?.frequency = Float(frequency)
internalAU?.amplitude = Float(amplitude)
}
/// Trigger the sound with an optional set of parameters
/// - frequency: Frequency in Hz
/// - amplitude amplitude: Volume
///
open func trigger(frequency: Double, amplitude: Double = 1) {
self.frequency = frequency
self.amplitude = amplitude
internalAU?.start()
internalAU?.triggerFrequency(Float(frequency), amplitude: Float(amplitude))
}
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
internalAU?.start()
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
internalAU?.stop()
}
}
| b7e22ee86c0ee7cf3e175505b1ccffa4 | 32.132353 | 113 | 0.617843 | false | false | false | false |
pyromobile/nubomedia-ouatclient-src | refs/heads/master | ios/LiveTales-smartphones/uoat/NotificationModel.swift | apache-2.0 | 2 | //
// NotificationModel.swift
// uoat
//
// Created by Pyro User on 28/7/16.
// Copyright © 2016 Zed. All rights reserved.
//
import Foundation
enum NotificationType
{
case Undefined
case ReadingRoom
case PlayingRoom
case FriendShip
}
class NotificationModel
{
class func getAllByUser(userId:String, onNotificationsReady:(notifications:[NotificationType:[Notification]])->Void)
{
var notificationsByType:[NotificationType:[Notification]] = [NotificationType:[Notification]]()
let criteria:[String:AnyObject] = ["to":"pub_\(userId)"]
let query = KuasarsQuery( criteria, retrievingFields: nil ) as KuasarsQuery
KuasarsEntity.query( query, entityType: "requests", occEnabled: false, completion:{ (response:KuasarsResponse!, error:KuasarsError!) -> Void in
if( error != nil )
{
print( "Error from kuasars: \(error.description)" )
}
else
{
let entities = response.contentObjects as! [KuasarsEntity]
for entity:KuasarsEntity in entities
{
let id:String = entity.ID
let type:String = (entity.customData![TypeField])! as! String
let from:String = (entity.customData![FromField])! as! String
let to:String = (entity.customData![ToField])! as! String
var roomId:String = ""
if( type == ReadingRoom || type == PlayingRoom )
{
roomId = (entity.customData![RoomIdField])! as! String
}
let typed = getTypeByName(type)
let notification = Notification( id:id, type:typed, from:from, to:to, roomId:roomId )
if var _ = notificationsByType[typed]
{
notificationsByType[typed]?.append( notification )
}
else
{
notificationsByType[typed] = [notification]
}
}
}
onNotificationsReady( notifications:notificationsByType )
})
}
class func getNickNamesFromNotifications( notifications:[Notification], onNotificationsReady:(notifications:[Notification])->Void )
{
let batch = KuasarsBatch()
for notification:Notification in notifications
{
let friendId:String = notification.getFrom()
let criteria:[String:AnyObject] = ["id":"\(friendId)"]
let query = KuasarsQuery( criteria, retrievingFields: nil ) as KuasarsQuery
let request:KuasarsRequest = KuasarsServices.queryEntities(query, type: "users", occEnabled: false)
batch.addRequest(request)
}
batch.performRequests({ (response:KuasarsResponse!, error:KuasarsError!) in
if( error != nil )
{
print( "Error from kuasars: \(error.description)" )
}
else
{
let responses = response.contentObjects as! [NSDictionary]
for index in 0 ..< responses.count
{
let rsp:NSDictionary = responses[index] as NSDictionary
let body:[NSDictionary] = rsp["body"] as! [NSDictionary]
let friendNick = body[0]["nick"] as! String
print("Request Amigo :\(friendNick)")
notifications[index].nickNameFrom = friendNick
}
}
onNotificationsReady( notifications: notifications )
})
}
class func getNickNamesFromSentNotifications( notifications:[Notification], onNotificationsReady:(notifications:[Notification])->Void )
{
let batch = KuasarsBatch()
for notification:Notification in notifications
{
let friendId:String = notification.getTo()
let criteria:[String:AnyObject] = ["id":"\(friendId)"]
let query = KuasarsQuery( criteria, retrievingFields: nil ) as KuasarsQuery
let request:KuasarsRequest = KuasarsServices.queryEntities(query, type: "users", occEnabled: false)
batch.addRequest(request)
}
batch.performRequests({ (response:KuasarsResponse!, error:KuasarsError!) in
if( error != nil )
{
print( "Error from kuasars: \(error.description)" )
}
else
{
let responses = response.contentObjects as! [NSDictionary]
for index in 0 ..< responses.count
{
let rsp:NSDictionary = responses[index] as NSDictionary
let body:[NSDictionary] = rsp["body"] as! [NSDictionary]
let friendNick = body[0]["nick"] as! String
print("Request Amigo :\(friendNick)")
notifications[index].nickNameFrom = friendNick
}
}
onNotificationsReady( notifications: notifications )
})
}
class func removeNotificationsById(notificationIds:[String], onNotificationsReady:()->Void)
{
KuasarsEntity.deleteEntitiesOfType("requests", withIds: notificationIds) { (response:KuasarsResponse!, error:KuasarsError!) in
if( error != nil )
{
print("Kuasars error:\(error.description)")
}
else
{
print("Removed")
}
onNotificationsReady()
}
}
class func sendNotifications(notifications:[Notification],onNotificationsReady:(error:Bool)->Void)
{
let serverTimeRequest:KuasarsRequest = KuasarsServices.getCurrentTime()
KuasarsCore.executeRequest(serverTimeRequest) { (response:KuasarsResponse!, error:KuasarsError!) in
if( error != nil )
{
print("Error get server time: \(error.description)")
}
else
{
let expire:Double = 10*60*1000 //Ten minutes!
//Get time from server.
let content:NSDictionary = response.contentObjects[0] as! NSDictionary
let serverTime:Double = content["timeInMillisFrom1970"] as! Double
let batch = KuasarsBatch()
for notification in notifications
{
let type:String = getNameByType( notification.getType() )
if( type.isEmpty ){ continue }
let friendId:String = notification.getTo()
let userId:String = notification.getFrom()
let roomId:String = notification.getRoomId()
//create friend request.
let entity = ["type":type,"to":friendId,"from":"pub_\(userId)","roomId":roomId,"expireAt":(serverTime + expire)]
let requestsEntity = KuasarsEntity(type: "requests", customData: entity as [NSObject : AnyObject], expirationDate:(serverTime + expire), occEnabled: false)
let acl = KuasarsPermissions()
acl.setReadPermissions( KuasarsReadPermissionALL, usersList: nil, groupList: nil )
requestsEntity.setPermissions( acl )
let request:KuasarsRequest = KuasarsServices.saveNewEntity(requestsEntity)
batch.addRequest( request )
}
batch.performRequests({ (response:KuasarsResponse!, error:KuasarsError!) in
onNotificationsReady(error:error != nil)
})
}
}
}
class func sendFriendshipRequest(userId:String, friendSecrectCode:String, friendNick:String,onFriendshipReady:(error:Bool)->Void)
{
//Check secrect code remote user & get time from server.
let criteria:[String:AnyObject] = ["code":friendSecrectCode, "nick":friendNick]
let query = KuasarsQuery( criteria, retrievingFields: nil ) as KuasarsQuery
let userQueryRequest:KuasarsRequest = KuasarsServices.queryEntities( query, type: "users", occEnabled: false)
let serverTimeRequest:KuasarsRequest = KuasarsServices.getCurrentTime()
let batch = KuasarsBatch()
batch.addRequest( userQueryRequest )
batch.addRequest( serverTimeRequest )
batch.performRequests { (response:KuasarsResponse!, error:KuasarsError!) in
if( error != nil )
{
print( "Error from kuasars: \(error.description)" )
onFriendshipReady( error:true )
}
else
{
//User exist?
let responses = response.contentObjects as! [NSDictionary]
let resp1 = responses[0] as NSDictionary
let userExists = ( resp1["code"] as! Int == 200 )
if( userExists )
{
let body1 = resp1["body"] as! NSArray
let friendID = body1[0]["id"] as! String
print("friend ID:\(friendID)")
//Server time.
let expire:Double = 24*60*60*1000
let resp2 = responses[1] as NSDictionary
let body2 = resp2["body"] as! NSDictionary
let serverTime:Double = body2["timeInMillisFrom1970"] as! Double
print("Server time:\(serverTime) - Add:\(expire)")
//create friend request.
let entity = ["type":"friendship","to":friendID,"from":"pub_\(userId)","expireAt":(serverTime + expire)]
let requestsEntity = KuasarsEntity(type: "requests", customData: entity as [NSObject : AnyObject], expirationDate:(serverTime + expire), occEnabled: false)
let acl = KuasarsPermissions()
acl.setReadPermissions( KuasarsReadPermissionALL, usersList: nil, groupList: nil )
requestsEntity.setPermissions( acl )
requestsEntity.save { ( response:KuasarsResponse!, error:KuasarsError! ) -> Void in
if( error != nil )
{
print( "Error from kuasars: \(error.description)" )
onFriendshipReady( error:true )
}
else
{
print("Request was sent!")
onFriendshipReady( error:false )
}
}
}
else
{
onFriendshipReady( error:true )
}
}
}
}
class func getNotificationsSentByMe(userId:String, onNotificationsReady:(notifications:[NotificationType:[Notification]])->Void)
{
var notificationsByType:[NotificationType:[Notification]] = [NotificationType:[Notification]]()
let criteria:[String:AnyObject] = ["from":"pub_\(userId)"]
let query = KuasarsQuery( criteria, retrievingFields: nil ) as KuasarsQuery
KuasarsEntity.query( query, entityType: "requests", occEnabled: false, completion:{ (response:KuasarsResponse!, error:KuasarsError!) -> Void in
if( error != nil )
{
print( "Error from kuasars: \(error.description)" )
}
else
{
let entities = response.contentObjects as! [KuasarsEntity]
for entity:KuasarsEntity in entities
{
let id:String = entity.ID
let type:String = (entity.customData![TypeField])! as! String
let from:String = (entity.customData![FromField])! as! String
let to:String = (entity.customData![ToField])! as! String
var roomId:String = ""
if( type == ReadingRoom || type == PlayingRoom )
{
roomId = (entity.customData![RoomIdField])! as! String
}
let typed = getTypeByName(type)
let notification = Notification( id:id, type:typed, from:from, to:to, roomId:roomId )
if var _ = notificationsByType[typed]
{
notificationsByType[typed]?.append( notification )
}
else
{
notificationsByType[typed] = [notification]
}
}
}
onNotificationsReady( notifications:notificationsByType )
})
}
/*=============================================================*/
/* Private Section */
/*=============================================================*/
private class func getTypeByName( typeName:String ) -> NotificationType
{
let notificationType:NotificationType
switch( typeName )
{
case ReadingRoom:
notificationType = .ReadingRoom
break
case PlayingRoom:
notificationType = .PlayingRoom
break
case FriendShip:
notificationType = .FriendShip
break
default:
notificationType = .Undefined
break
}
return notificationType
}
private class func getNameByType( type:NotificationType ) -> String
{
let name:String
switch( type )
{
case .ReadingRoom:
name = ReadingRoom
break
case .PlayingRoom:
name = PlayingRoom
break
case .FriendShip:
name = FriendShip
break
default:
name = ""
}
return name
}
//Fields.
private static let TypeField:String = "type"
private static let FromField:String = "from"
private static let ToField:String = "to"
private static let RoomIdField:String = "roomId"
//Types.
private static let ReadingRoom:String = "readingroom"
private static let PlayingRoom:String = "playingroom"
private static let FriendShip:String = "friendship"
} | f79ab8557ba4014134a50a19309270fe | 39.626016 | 175 | 0.515744 | false | false | false | false |
shohei/firefox-ios | refs/heads/master | Client/Frontend/Browser/TabManager.swift | mpl-2.0 | 1 | /* 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 WebKit
import Storage
import Shared
protocol TabManagerDelegate: class {
func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?)
func tabManager(tabManager: TabManager, didCreateTab tab: Browser, restoring: Bool)
func tabManager(tabManager: TabManager, didAddTab tab: Browser, atIndex: Int, restoring: Bool)
func tabManager(tabManager: TabManager, didRemoveTab tab: Browser, atIndex index: Int)
func tabManagerDidRestoreTabs(tabManager: TabManager)
}
// We can't use a WeakList here because this is a protocol.
class WeakTabManagerDelegate {
weak var value : TabManagerDelegate?
init (value: TabManagerDelegate) {
self.value = value
}
func get() -> TabManagerDelegate? {
return value
}
}
// TabManager must extend NSObjectProtocol in order to implement WKNavigationDelegate
class TabManager : NSObject {
private var delegates = [WeakTabManagerDelegate]()
func addDelegate(delegate: TabManagerDelegate) {
assert(NSThread.isMainThread())
delegates.append(WeakTabManagerDelegate(value: delegate))
}
func removeDelegate(delegate: TabManagerDelegate) {
assert(NSThread.isMainThread())
for var i = 0; i < delegates.count; i++ {
var del = delegates[i]
if delegate === del.get() {
delegates.removeAtIndex(i)
return
}
}
}
private var tabs: [Browser] = []
private var _selectedIndex = -1
var selectedIndex: Int { return _selectedIndex }
private let defaultNewTabRequest: NSURLRequest
private let navDelegate: TabManagerNavDelegate
private var configuration: WKWebViewConfiguration
let storage: RemoteClientsAndTabs?
private let prefs: Prefs
init(defaultNewTabRequest: NSURLRequest, storage: RemoteClientsAndTabs? = nil, prefs: Prefs) {
// Create a common webview configuration with a shared process pool.
configuration = WKWebViewConfiguration()
configuration.processPool = WKProcessPool()
configuration.preferences.javaScriptCanOpenWindowsAutomatically = !(prefs.boolForKey("blockPopups") ?? true)
self.defaultNewTabRequest = defaultNewTabRequest
self.storage = storage
self.navDelegate = TabManagerNavDelegate()
self.prefs = prefs
super.init()
addNavigationDelegate(self)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "prefsDidChange", name: NSUserDefaultsDidChangeNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func addNavigationDelegate(delegate: WKNavigationDelegate) {
self.navDelegate.insert(delegate)
}
var count: Int {
return tabs.count
}
var selectedTab: Browser? {
if !(0..<count ~= _selectedIndex) {
return nil
}
return tabs[_selectedIndex]
}
subscript(index: Int) -> Browser? {
if index >= tabs.count {
return nil
}
return tabs[index]
}
subscript(webView: WKWebView) -> Browser? {
for tab in tabs {
if tab.webView === webView {
return tab
}
}
return nil
}
func selectTab(tab: Browser?) {
assert(NSThread.isMainThread())
if selectedTab === tab {
return
}
let previous = selectedTab
_selectedIndex = -1
for i in 0..<count {
if tabs[i] === tab {
_selectedIndex = i
break
}
}
assert(tab === selectedTab, "Expected tab is selected")
selectedTab?.createWebview()
for delegate in delegates {
delegate.get()?.tabManager(self, didSelectedTabChange: tab, previous: previous)
}
}
// This method is duplicated to hide the flushToDisk option from consumers.
func addTab(var request: NSURLRequest! = nil, configuration: WKWebViewConfiguration! = nil) -> Browser {
return self.addTab(request: request, configuration: configuration, flushToDisk: true, zombie: false)
}
func addTab(var request: NSURLRequest! = nil, configuration: WKWebViewConfiguration! = nil, flushToDisk: Bool, zombie: Bool, restoring: Bool = false) -> Browser {
assert(NSThread.isMainThread())
configuration?.preferences.javaScriptCanOpenWindowsAutomatically = !(prefs.boolForKey("blockPopups") ?? true)
let tab = Browser(configuration: configuration ?? self.configuration)
for delegate in delegates {
delegate.get()?.tabManager(self, didCreateTab: tab, restoring: restoring)
}
tabs.append(tab)
for delegate in delegates {
delegate.get()?.tabManager(self, didAddTab: tab, atIndex: tabs.count - 1, restoring: restoring)
}
if !zombie {
tab.createWebview()
}
tab.navigationDelegate = self.navDelegate
tab.loadRequest(request ?? defaultNewTabRequest)
if flushToDisk {
storeChanges()
}
return tab
}
// This method is duplicated to hide the flushToDisk option from consumers.
func removeTab(tab: Browser) {
self.removeTab(tab, flushToDisk: true)
}
private func removeTab(tab: Browser, flushToDisk: Bool) {
assert(NSThread.isMainThread())
// If the removed tab was selected, find the new tab to select.
if tab === selectedTab {
let index = getIndex(tab)
if index + 1 < count {
selectTab(tabs[index + 1])
} else if index - 1 >= 0 {
selectTab(tabs[index - 1])
} else {
assert(count == 1, "Removing last tab")
selectTab(nil)
}
}
let prevCount = count
var index = -1
for i in 0..<count {
if tabs[i] === tab {
tabs.removeAtIndex(i)
index = i
break
}
}
assert(count == prevCount - 1, "Tab removed")
// There's still some time between this and the webView being destroyed.
// We don't want to pick up any stray events.
tab.webView?.navigationDelegate = nil
for delegate in delegates {
delegate.get()?.tabManager(self, didRemoveTab: tab, atIndex: index)
}
if flushToDisk {
storeChanges()
}
}
func removeAll() {
let tabs = self.tabs
for tab in tabs {
self.removeTab(tab, flushToDisk: false)
}
storeChanges()
}
func getIndex(tab: Browser) -> Int {
for i in 0..<count {
if tabs[i] === tab {
return i
}
}
assertionFailure("Tab not in tabs list")
return -1
}
private func storeChanges() {
// It is possible that not all tabs have loaded yet, so we filter out tabs with a nil URL.
let storedTabs: [RemoteTab] = optFilter(tabs.map(Browser.toTab))
storage?.insertOrUpdateTabs(storedTabs)
// Also save (full) tab state to disk
preserveTabs()
}
func prefsDidChange() {
let allowPopups = !(prefs.boolForKey("blockPopups") ?? true)
for tab in tabs {
tab.webView?.configuration.preferences.javaScriptCanOpenWindowsAutomatically = allowPopups
}
}
}
extension TabManager {
class SavedTab: NSObject, NSCoding {
let isSelected: Bool
let screenshot: UIImage?
var sessionData: SessionData?
init?(browser: Browser, isSelected: Bool) {
let currentItem = browser.webView?.backForwardList.currentItem
if browser.sessionData == nil {
let backList = browser.webView?.backForwardList.backList as? [WKBackForwardListItem] ?? []
let forwardList = browser.webView?.backForwardList.forwardList as? [WKBackForwardListItem] ?? []
let currentList = (currentItem != nil) ? [currentItem!] : []
var urlList = backList + currentList + forwardList
var updatedUrlList = [NSURL]()
for url in urlList {
updatedUrlList.append(url.URL)
}
var currentPage = -forwardList.count
self.sessionData = SessionData(currentPage: currentPage, urls: updatedUrlList)
} else {
self.sessionData = browser.sessionData
}
self.screenshot = browser.screenshot
self.isSelected = isSelected
super.init()
}
required init(coder: NSCoder) {
self.sessionData = coder.decodeObjectForKey("sessionData") as? SessionData
self.screenshot = coder.decodeObjectForKey("screenshot") as? UIImage
self.isSelected = coder.decodeBoolForKey("isSelected")
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(sessionData, forKey: "sessionData")
coder.encodeObject(screenshot, forKey: "screenshot")
coder.encodeBool(isSelected, forKey: "isSelected")
}
}
private func tabsStateArchivePath() -> String? {
if let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as? String {
return documentsPath.stringByAppendingPathComponent("tabsState.archive")
}
return nil
}
private func preserveTabsInternal() {
if let path = tabsStateArchivePath() {
var savedTabs = [SavedTab]()
for (tabIndex, tab) in enumerate(tabs) {
if let savedTab = SavedTab(browser: tab, isSelected: tabIndex == selectedIndex) {
savedTabs.append(savedTab)
}
}
let tabStateData = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: tabStateData)
archiver.encodeObject(savedTabs, forKey: "tabs")
archiver.finishEncoding()
tabStateData.writeToFile(path, atomically: true)
}
}
func preserveTabs() {
// This is wrapped in an Objective-C @try/@catch handler because NSKeyedArchiver may throw exceptions which Swift cannot handle
Try(
try: { () -> Void in
self.preserveTabsInternal()
},
catch: { exception in
println("Failed to preserve tabs: \(exception)")
}
)
}
private func restoreTabsInternal() {
if let tabStateArchivePath = tabsStateArchivePath() {
if NSFileManager.defaultManager().fileExistsAtPath(tabStateArchivePath) {
if let data = NSData(contentsOfFile: tabStateArchivePath) {
let unarchiver = NSKeyedUnarchiver(forReadingWithData: data)
if let savedTabs = unarchiver.decodeObjectForKey("tabs") as? [SavedTab] {
var tabToSelect: Browser?
for (tabIndex, savedTab) in enumerate(savedTabs) {
let tab = self.addTab(flushToDisk: false, zombie: true, restoring: true)
tab.screenshot = savedTab.screenshot
if savedTab.isSelected {
tabToSelect = tab
}
tab.sessionData = savedTab.sessionData
}
if tabToSelect == nil {
tabToSelect = tabs.first
}
for delegate in delegates {
delegate.get()?.tabManagerDidRestoreTabs(self)
}
if let tab = tabToSelect {
selectTab(tab)
tab.createWebview()
}
}
}
}
}
}
func restoreTabs() {
// This is wrapped in an Objective-C @try/@catch handler because NSKeyedUnarchiver may throw exceptions which Swift cannot handle
Try(
try: { () -> Void in
self.restoreTabsInternal()
},
catch: { exception in
println("Failed to restore tabs: \(exception)")
}
)
}
}
extension TabManager : WKNavigationDelegate {
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
storeChanges()
}
}
// WKNavigationDelegates must implement NSObjectProtocol
class TabManagerNavDelegate : NSObject, WKNavigationDelegate {
private var delegates = WeakList<WKNavigationDelegate>()
func insert(delegate: WKNavigationDelegate) {
delegates.insert(delegate)
}
func webView(webView: WKWebView, didCommitNavigation navigation: WKNavigation!) {
for delegate in delegates {
delegate.webView?(webView, didCommitNavigation: navigation)
}
}
func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
for delegate in delegates {
delegate.webView?(webView, didFailNavigation: navigation, withError: error)
}
}
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!,
withError error: NSError) {
for delegate in delegates {
delegate.webView?(webView, didFailProvisionalNavigation: navigation, withError: error)
}
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
for delegate in delegates {
delegate.webView?(webView, didFinishNavigation: navigation)
}
}
func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition,
NSURLCredential!) -> Void) {
var disp: NSURLSessionAuthChallengeDisposition? = nil
for delegate in delegates {
delegate.webView?(webView, didReceiveAuthenticationChallenge: challenge) { (disposition, credential) in
// Whoever calls this method first wins. All other calls are ignored.
if disp != nil {
return
}
disp = disposition
completionHandler(disposition, credential)
}
}
}
func webView(webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
for delegate in delegates {
delegate.webView?(webView, didReceiveServerRedirectForProvisionalNavigation: navigation)
}
}
func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
for delegate in delegates {
delegate.webView?(webView, didStartProvisionalNavigation: navigation)
}
}
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction,
decisionHandler: (WKNavigationActionPolicy) -> Void) {
var res = WKNavigationActionPolicy.Allow
for delegate in delegates {
delegate.webView?(webView, decidePolicyForNavigationAction: navigationAction, decisionHandler: { policy in
if policy == .Cancel {
res = policy
}
})
}
decisionHandler(res)
}
func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse,
decisionHandler: (WKNavigationResponsePolicy) -> Void) {
var res = WKNavigationResponsePolicy.Allow
for delegate in delegates {
delegate.webView?(webView, decidePolicyForNavigationResponse: navigationResponse, decisionHandler: { policy in
if policy == .Cancel {
res = policy
}
})
}
decisionHandler(res)
}
}
| 97d779f3c4f537954ad302e64b9ec7d2 | 33.834034 | 166 | 0.598275 | false | false | false | false |
objecthub/swift-lispkit | refs/heads/master | Sources/LispKit/Data/Expr.swift | apache-2.0 | 1 | //
// Expr.swift
// LispKit
//
// Created by Matthias Zenger on 08/11/2015.
// Copyright © 2016-2022 ObjectHub. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import NumberKit
///
/// `Expr` represents LispKit expressions in form of an enumeration with associated values.
///
public enum Expr: Hashable {
case undef
case void
case eof
case null
case `true`
case `false`
case uninit(Symbol)
case symbol(Symbol)
case fixnum(Int64)
case bignum(BigInt)
indirect case rational(Expr, Expr)
case flonum(Double)
case complex(DoubleComplex)
case char(UniChar)
case string(NSMutableString)
case bytes(ByteVector)
indirect case pair(Expr, Expr)
case box(Cell)
case mpair(Tuple)
case array(Collection)
case vector(Collection)
case record(Collection)
case table(HashTable)
case promise(Promise)
indirect case values(Expr)
case procedure(Procedure)
case special(SpecialForm)
case env(Environment)
case port(Port)
case object(NativeObject)
indirect case tagged(Expr, Expr)
case error(RuntimeError)
indirect case syntax(SourcePosition, Expr)
/// Returns the type of this expression.
public var type: Type {
switch self {
case .undef, .uninit(_):
return .undefinedType
case .void:
return .voidType
case .eof:
return .eofType
case .null:
return .nullType
case .true:
return .booleanType
case .false:
return .booleanType
case .symbol(_):
return .symbolType
case .fixnum(_):
return .fixnumType
case .bignum(_):
return .bignumType
case .rational(_, _):
return .rationalType
case .flonum(let num):
return Foundation.trunc(num) == num ? .integerType : .floatType
case .complex(_):
return .complexType
case .char(_):
return .charType
case .string(_):
return .strType
case .bytes(_):
return .byteVectorType
case .pair(_, _):
return .pairType
case .box(_):
return .boxType
case .mpair(_):
return .mpairType
case .array(_):
return .arrayType
case .vector(let vec):
return vec.isGrowableVector ? .gvectorType : .vectorType
case .record(_):
return .recordType
case .table(_):
return .tableType
case .promise(let future):
return future.isStream ? .streamType : .promiseType
case .values(_):
return .valuesType
case .procedure(_):
return .procedureType
case .special(_):
return .specialType
case .env(_):
return .envType
case .port(_):
return .portType
case .object(let obj):
return obj.type
case .tagged(_, _):
return .taggedType
case .error(_):
return .errorType
case .syntax(_, _):
return .syntaxType
}
}
/// Returns the position of this expression.
public var pos: SourcePosition {
switch self {
case .syntax(let sourcePos, _):
return sourcePos
default:
return SourcePosition.unknown
}
}
// Predicate methods
/// Returns true if this expression is undefined.
public var isUndef: Bool {
switch self {
case .undef, .uninit(_):
return true
default:
return false
}
}
/// Returns true if this expression is null.
public var isNull: Bool {
switch self {
case .null:
return true
default:
return false
}
}
/// Returns true if this is not the `#f` value.
public var isTrue: Bool {
switch self {
case .false:
return false
default:
return true
}
}
/// Returns true if this is the `#f` value.
public var isFalse: Bool {
switch self {
case .false:
return true
default:
return false
}
}
/// Returns true if this is an exact number.
public var isExactNumber: Bool {
switch self {
case .fixnum(_), .bignum(_), .rational(_, _):
return true
default:
return false
}
}
/// Returns true if this is an inexact number.
public var isInexactNumber: Bool {
switch self {
case .flonum(_), .complex(_):
return true
default:
return false
}
}
/// Normalizes the representation (relevant for numeric datatypes)
public var normalized: Expr {
switch self {
case .bignum(let num):
if let fn = num.intValue {
return .fixnum(fn)
}
return self
case .rational(let n, let d):
switch d {
case .fixnum(let fd):
return fd == 1 ? n : self
case .bignum(let bd):
return bd == 1 ? n.normalized : self
default:
return self
}
case .complex(let num):
return num.value.isReal ? .flonum(num.value.re) : self
default:
return self
}
}
/// Returns the source position associated with this expression, or `outer` in case there is
/// no syntax annotation.
public func pos(_ outer: SourcePosition = SourcePosition.unknown) -> SourcePosition {
switch self {
case .syntax(let p, _):
return p
case .pair(.syntax(let p, _), _):
return p
default:
return outer
}
}
/// Returns the given expression with all symbols getting interned and syntax nodes removed.
public var datum: Expr {
switch self {
case .symbol(let sym):
return .symbol(sym.root)
case .pair(let car, let cdr):
return .pair(car.datum, cdr.datum)
case .syntax(_, let expr):
return expr.datum
default:
return self
}
}
/// Returns the given expression with all syntax nodes removed up to `depth` nested expression
/// nodes.
public func removeSyntax(depth: Int = 4) -> Expr {
guard depth > 0 else {
return self
}
switch self {
case .pair(let car, let cdr):
return .pair(car.removeSyntax(depth: depth - 1), cdr.removeSyntax(depth: depth - 1))
case .syntax(_, let expr):
return expr.removeSyntax(depth: depth)
default:
return self
}
}
/// Inject the given position into the expression.
public func at(pos: SourcePosition) -> Expr {
switch self {
case .pair(let car, let cdr):
return .syntax(pos, .pair(car.at(pos: pos), cdr.at(pos: pos)))
case .syntax(_, _):
return self
default:
return .syntax(pos, self)
}
}
/// Maps a list into an array of expressions and a tail (= null for proper lists)
public func toExprs() -> (Exprs, Expr) {
var exprs = Exprs()
var expr = self
while case .pair(let car, let cdr) = expr {
exprs.append(car)
expr = cdr
}
return (exprs, expr)
}
/// The length of this expression (all non-pair expressions have length 1).
var length: Int {
var expr = self
var len = 0
while case .pair(_, let cdr) = expr {
len += 1
expr = cdr
}
return len
}
/// Returns true if the expression isn't referring to other expressions directly or
/// indirectly.
public var isAtom: Bool {
switch self {
case .undef, .void, .eof, .null, .true, .false, .uninit(_), .symbol(_),
.fixnum(_), .bignum(_), .rational(_, _), .flonum(_), .complex(_),
.char(_), .string(_), .bytes(_), .env(_), .port(_), .object(_):
return true
case .pair(let car0, .pair(let car1, .pair(let car2, let cdr))):
return car0.isSimpleAtom && car1.isSimpleAtom && car2.isSimpleAtom && cdr.isSimpleAtom
case .pair(let car0, .pair(let car1, let cdr)):
return car0.isSimpleAtom && car1.isSimpleAtom && cdr.isSimpleAtom
case .pair(let car, let cdr):
return car.isSimpleAtom && cdr.isSimpleAtom
case .tagged(let tag, let expr):
return tag.isSimpleAtom && expr.isAtom
case .values(let expr):
return expr.isAtom
default:
return false
}
}
public var isSimpleAtom: Bool {
switch self {
case .undef, .void, .eof, .null, .true, .false, .uninit(_), .symbol(_),
.fixnum(_), .bignum(_), .rational(_, _), .flonum(_), .complex(_),
.char(_), .string(_), .bytes(_), .env(_), .port(_), .object(_):
return true
default:
return false
}
}
public func hash(into hasher: inout Hasher) {
equalHash(self, into: &hasher)
}
}
/// Extension adding static factory methods to `Expr`.
///
extension Expr {
public static func makeBoolean(_ val: Bool) -> Expr {
return val ? .true : .false
}
public static func makeNumber(_ num: Int) -> Expr {
return .fixnum(Int64(num))
}
public static func makeNumber(_ num: Int64) -> Expr {
return .fixnum(num)
}
public static func makeNumber(_ num: UInt64) -> Expr {
return Expr.bignum(BigInt(num)).normalized
}
public static func makeNumber(_ num: BigInt) -> Expr {
return Expr.bignum(num).normalized
}
public static func makeNumber(_ num: Rational<Int64>) -> Expr {
return Expr.rational(.fixnum(num.numerator), .fixnum(num.denominator)).normalized
}
public static func makeNumber(_ num: Rational<BigInt>) -> Expr {
return Expr.rational(.bignum(num.numerator), .bignum(num.denominator)).normalized
}
public static func makeNumber(_ num: Double) -> Expr {
return .flonum(num)
}
public static func makeNumber(_ num: Complex<Double>) -> Expr {
return Expr.complex(ImmutableBox(num)).normalized
}
public static func makeList(_ expr: Expr...) -> Expr {
return Expr.makeList(fromStack: expr.reversed(), append: Expr.null)
}
public static func makeList(_ exprs: Exprs, append: Expr = Expr.null) -> Expr {
return Expr.makeList(fromStack: exprs.reversed(), append: append)
}
public static func makeList(_ exprs: Arguments, append: Expr = Expr.null) -> Expr {
return Expr.makeList(fromStack: exprs.reversed(), append: append)
}
public static func makeList(fromStack exprs: [Expr], append: Expr = Expr.null) -> Expr {
var res = append
for expr in exprs {
res = pair(expr, res)
}
return res
}
public static func makeString(_ str: String) -> Expr {
return .string(NSMutableString(string: str))
}
}
/// This extension adds projections to `Expr`.
///
extension Expr {
@inline(__always)
public func assertType(at pos: SourcePosition = SourcePosition.unknown, _ types: Type...) throws {
for type in types {
for subtype in type.included {
if self.type == subtype {
return
}
}
}
throw RuntimeError.type(self, expected: Set(types)).at(pos)
}
@inline(__always)
public func asInt64(at pos: SourcePosition = SourcePosition.unknown) throws -> Int64 {
guard case .fixnum(let res) = self else {
throw RuntimeError.type(self, expected: [.fixnumType]).at(pos)
}
return res
}
@inline(__always)
public func asInt(above: Int = 0, below: Int = Int.max) throws -> Int {
guard case .fixnum(let res) = self else {
throw RuntimeError.type(self, expected: [.fixnumType])
}
guard res >= Int64(above) && res < Int64(below) else {
throw RuntimeError.range(self,
min: Int64(above),
max: below == Int.max ? Int64.max : Int64(below - 1))
}
return Int(res)
}
@inline(__always) public func asUInt8() throws -> UInt8 {
guard case .fixnum(let number) = self , number >= 0 && number <= 255 else {
throw RuntimeError.type(self, expected: [.byteType])
}
return UInt8(number)
}
public func asDouble(coerce: Bool = false) throws -> Double {
if !coerce {
if case .flonum(let num) = self {
return num
}
throw RuntimeError.type(self, expected: [.floatType])
}
switch self.normalized {
case .fixnum(let num):
return Double(num)
case .bignum(let num):
return num.doubleValue
case .rational(.fixnum(let n), .fixnum(let d)):
return Double(n) / Double(d)
case .rational(.bignum(let n), .bignum(let d)):
return n.doubleValue / d.doubleValue
case .flonum(let num):
return num
default:
throw RuntimeError.type(self, expected: [.realType])
}
}
public func asComplex(coerce: Bool = false) throws -> Complex<Double> {
if !coerce {
switch self {
case .flonum(let num):
return Complex(num, 0.0)
case .complex(let complex):
return complex.value
default:
throw RuntimeError.type(self, expected: [.complexType])
}
}
switch self.normalized {
case .fixnum(let num):
return Complex(Double(num), 0.0)
case .bignum(let num):
return Complex(num.doubleValue, 0.0)
case .rational(.fixnum(let n), .fixnum(let d)):
return Complex(Double(n) / Double(d), 0.0)
case .rational(.bignum(let n), .bignum(let d)):
return Complex(n.doubleValue / d.doubleValue, 0.0)
case .flonum(let num):
return Complex(num, 0.0)
case .complex(let num):
return num.value
default:
throw RuntimeError.type(self, expected: [.complexType])
}
}
@inline(__always) public func asSymbol() throws -> Symbol {
switch self {
case .symbol(let sym):
return sym
default:
throw RuntimeError.type(self, expected: [.symbolType])
}
}
@inline(__always) public func toSymbol() -> Symbol? {
switch self {
case .symbol(let sym):
return sym
default:
return nil
}
}
@inline(__always) public func asUniChar() throws -> UniChar {
guard case .char(let res) = self else {
throw RuntimeError.type(self, expected: [.charType])
}
return res
}
@inline(__always) public func charAsString() throws -> String {
guard case .char(let res) = self else {
throw RuntimeError.type(self, expected: [.charType])
}
return String(unicodeScalar(res))
}
@inline(__always) public func charOrString() throws -> String {
switch self {
case .char(let res):
return String(unicodeScalar(res))
case .string(let res):
return res as String
default:
throw RuntimeError.type(self, expected: [.strType])
}
}
@inline(__always) public func asString() throws -> String {
guard case .string(let res) = self else {
throw RuntimeError.type(self, expected: [.strType])
}
return res as String
}
@inline(__always) public func asMutableStr() throws -> NSMutableString {
guard case .string(let res) = self else {
throw RuntimeError.type(self, expected: [.strType])
}
return res
}
@inline(__always) public func asPath() throws -> String {
guard case .string(let res) = self else {
throw RuntimeError.type(self, expected: [.strType])
}
return res.expandingTildeInPath
}
@inline(__always) public func asURL() throws -> URL {
guard case .string(let res) = self else {
throw RuntimeError.type(self, expected: [.strType])
}
guard let url = URL(string: res as String) else {
throw RuntimeError.eval(.invalidUrl, self)
}
return url
}
@inline(__always) public func asByteVector() throws -> ByteVector {
guard case .bytes(let bvector) = self else {
throw RuntimeError.type(self, expected: [.byteVectorType])
}
return bvector
}
@inline(__always) public func arrayAsCollection() throws -> Collection {
guard case .array(let res) = self else {
throw RuntimeError.type(self, expected: [.arrayType])
}
return res
}
@inline(__always) public func vectorAsCollection(growable: Bool? = nil) throws -> Collection {
guard case .vector(let vec) = self else {
let exp: Set<Type> = growable == nil ? [.vectorType, .gvectorType]
: growable! ? [.gvectorType] : [.vectorType]
throw RuntimeError.type(self, expected: exp)
}
if let growable = growable, growable != vec.isGrowableVector {
throw RuntimeError.type(self, expected: growable ? [.gvectorType] : [.vectorType])
}
return vec
}
@inline(__always) public func recordAsCollection() throws -> Collection {
guard case .record(let res) = self else {
throw RuntimeError.type(self, expected: [.recordType])
}
return res
}
@inline(__always) public func asHashTable() throws -> HashTable {
guard case .table(let map) = self else {
throw RuntimeError.type(self, expected: [.tableType])
}
return map
}
@inline(__always) public func asProcedure() throws -> Procedure {
guard case .procedure(let proc) = self else {
throw RuntimeError.type(self, expected: [.procedureType])
}
return proc
}
@inline(__always) public func asEnvironment() throws -> Environment {
guard case .env(let environment) = self else {
throw RuntimeError.type(self, expected: [.envType])
}
return environment
}
@inline(__always) public func asPort() throws -> Port {
guard case .port(let port) = self else {
throw RuntimeError.type(self, expected: [.portType])
}
return port
}
@inline(__always) public func asObject(of type: Type) throws -> NativeObject {
guard case .object(let obj) = self, obj.type == type else {
throw RuntimeError.type(self, expected: [type])
}
return obj
}
}
/// This extension makes `Expr` implement the `CustomStringConvertible`.
///
extension Expr: CustomStringConvertible {
public var description: String {
return self.toString()
}
public var unescapedDescription: String {
return self.toString(escape: false)
}
public func toString(escape: Bool = true) -> String {
var enclObjs = Set<Reference>()
var objId = [Reference: Int]()
func objIdString(_ ref: Reference) -> String? {
if let id = objId[ref] {
return "#\(id)#"
} else if enclObjs.contains(ref) {
objId[ref] = objId.count
return "#\(objId.count - 1)#"
} else {
return nil
}
}
func fixString(_ ref: Reference, _ str: String) -> String {
if let id = objId[ref] {
return "#\(id)=\(str)"
} else {
return str
}
}
func doubleString(_ val: Double) -> String {
if val.isInfinite {
return (val.sign == .minus) ? "-inf.0" : "+inf.0"
} else if val.isNaN {
return (val.sign == .minus) ? "-nan.0" : "+nan.0"
} else {
return String(val)
}
}
func stringReprOf(_ expr: Expr) -> String {
switch expr {
case .undef:
return "#<undef>"
case .void:
return "#<void>"
case .eof:
return "#<eof>"
case .null:
return "()"
case .true:
return "#t"
case .false:
return "#f"
case .uninit(let sym):
guard escape else {
return "#<uninit \(sym.rawIdentifier)>"
}
return "#<uninit \(sym.description)>"
case .symbol(let sym):
guard escape else {
return sym.rawIdentifier
}
return sym.description
case .fixnum(let val):
return String(val)
case .bignum(let val):
return val.description
case .rational(let n, let d):
return stringReprOf(n) + "/" + stringReprOf(d)
case .flonum(let val):
return doubleString(val)
case .complex(let val):
var res = doubleString(val.value.re)
if val.value.im.isNaN || val.value.im.isInfinite || val.value.im < 0.0 {
res += doubleString(val.value.im)
} else {
res += "+" + doubleString(val.value.im)
}
return res + "i"
case .char(let ch):
guard escape else {
return String(unicodeScalar(ch))
}
switch ch {
case 7: return "#\\alarm"
case 8: return "#\\backspace"
case 127: return "#\\delete"
case 27: return "#\\escape"
case 10: return "#\\newline"
case 0: return "#\\null"
case 12: return "#\\page"
case 13: return "#\\return"
case 32: return "#\\space"
case 9: return "#\\tab"
case 11: return "#\\vtab"
default :
if WHITESPACES_NL.contains(unicodeScalar(ch)) ||
CONTROL_CHARS.contains(unicodeScalar(ch)) ||
ILLEGAL_CHARS.contains(unicodeScalar(ch)) ||
MODIFIER_CHARS.contains(unicodeScalar(ch)) ||
ch > 0xd7ff {
return "#\\x\(String(ch, radix:16))"
} else if let scalar = UnicodeScalar(ch) {
return "#\\\(Character(scalar))"
} else {
return "#\\x\(String(ch, radix:16))"
}
}
case .string(let str):
guard escape else {
return str as String
}
return "\"\(Expr.escapeStr(str as String))\""
case .bytes(let boxedVec):
var builder = StringBuilder(prefix: "#u8(", postfix: ")", separator: " ")
for byte in boxedVec.value {
builder.append(String(byte))
}
return builder.description
case .pair(let head, let tail):
var builder = StringBuilder(prefix: "(", separator: " ")
builder.append(stringReprOf(head))
var expr = tail
while case .pair(let car, let cdr) = expr {
builder.append(stringReprOf(car))
expr = cdr
}
return builder.description + (expr.isNull ? ")" : " . \(stringReprOf(expr)))")
case .box(let cell):
if let res = objIdString(cell) {
return res
} else {
enclObjs.insert(cell)
let res = "#<box \(stringReprOf(cell.value))>"
enclObjs.remove(cell)
return fixString(cell, res)
}
case .mpair(let tuple):
if let res = objIdString(tuple) {
return res
} else {
enclObjs.insert(tuple)
let res = "#<pair \(stringReprOf(tuple.fst)) \(stringReprOf(tuple.snd))>"
enclObjs.remove(tuple)
return fixString(tuple, res)
}
case .array(let array):
if let res = objIdString(array) {
return res
} else if array.exprs.count == 0 {
return "#<array>"
} else {
enclObjs.insert(array)
var builder = StringBuilder(prefix: "#<array ", postfix: ">", separator: " ")
for expr in array.exprs {
builder.append(stringReprOf(expr))
}
enclObjs.remove(array)
return fixString(array, builder.description)
}
case .vector(let vector):
if let res = objIdString(vector) {
return res
} else if vector.exprs.count == 0 {
return vector.isGrowableVector ? "#g()" : "#()"
} else {
enclObjs.insert(vector)
var builder = StringBuilder(prefix: vector.isGrowableVector ? "#g(" : "#(",
postfix: ")",
separator: " ")
for expr in vector.exprs {
builder.append(stringReprOf(expr))
}
enclObjs.remove(vector)
return fixString(vector, builder.description)
}
case .record(let record):
guard case .record(let type) = record.kind else {
guard record.exprs.count > 0 else {
preconditionFailure("incorrect internal record type state: \(record.kind) | " +
"\(record.description)")
}
guard case .symbol(let sym) = record.exprs[0] else {
preconditionFailure("incorrect encoding of record type")
}
return "#<record-type \(sym.description)>"
}
if let res = objIdString(record) {
return res
} else {
guard case .symbol(let sym) = type.exprs[0] else {
preconditionFailure("incorrect encoding of record type")
}
enclObjs.insert(record)
var builder = StringBuilder(prefix: "#<record \(sym.description)",
postfix: ">",
separator: ", ",
initial: ": ")
var fields = type.exprs[2]
for expr in record.exprs {
guard case .pair(let sym, let nextFields) = fields else {
preconditionFailure("incorrect encoding of record \(type.exprs[0].description)")
}
builder.append(sym.description, "=", stringReprOf(expr))
fields = nextFields
}
enclObjs.remove(record)
return fixString(record, builder.description)
}
case .table(let map):
if let res = objIdString(map) {
return res
} else {
enclObjs.insert(map)
let prefix = Context.simplifiedDescriptions ?
"#<hashtable" : "#<hashtable \(map.identityString)"
var builder = StringBuilder(prefix: prefix,
postfix: ">",
separator: ", ",
initial: ": ")
for (key, value) in map.mappings {
builder.append(stringReprOf(key), " -> ", stringReprOf(value))
}
enclObjs.remove(map)
return fixString(map, builder.description)
}
case .promise(let promise):
return "#<\(promise.kind) \(promise.identityString)>"
case .values(let list):
var builder = StringBuilder(prefix: "#<values",
postfix: ">",
separator: " ",
initial: ": ")
var expr = list
while case .pair(let car, let cdr) = expr {
builder.append(stringReprOf(car))
expr = cdr
}
return builder.description
case .procedure(let proc):
switch proc.kind {
case .parameter(let tuple):
if let res = objIdString(proc) {
return res
} else {
enclObjs.insert(proc)
let res = "#<parameter \(proc.name): \(stringReprOf(tuple.snd))>"
enclObjs.remove(proc)
return fixString(proc, res)
}
case .rawContinuation(_):
return "#<raw-continuation \(proc.embeddedName)>"
case .closure(.continuation, _, _, _):
return "#<continuation \(proc.embeddedName)>"
default:
return "#<procedure \(proc.embeddedName)>"
}
case .special(let special):
return "#<special \(special.name)>"
case .env(let environment):
var type: String = ""
switch environment.kind {
case .library(let name):
type = " " + name.description
case .program(let filename):
type = " " + filename
case .repl:
type = " interaction"
case .custom:
type = ""
}
var builder = StringBuilder(prefix: "#<env",
postfix: ">",
separator: ", ",
initial: type + ": ")
for sym in environment.boundSymbols {
builder.append(sym.description)
}
return builder.description
case .port(let port):
return "#<\(port.typeDescription) \(port.identDescription)>"
case .object(let obj):
return obj.string
case .tagged(.pair(let fst, _), let expr):
var res = "#<"
switch fst {
case .pair(let head, let tail):
var builder = StringBuilder(prefix: "", separator: " ")
builder.append(stringReprOf(head))
var expr = tail
while case .pair(let car, let cdr) = expr {
builder.append(stringReprOf(car))
expr = cdr
}
if expr.isNull {
res += builder.description + ": "
} else {
res += builder.description + " . \(stringReprOf(expr)): "
}
case .object(let obj):
res += obj.tagString + " "
default:
res += stringReprOf(fst) + " "
}
switch expr {
case .object(let obj):
res += obj.tagString.truncated(limit: 100)
case .pair(let head, let tail):
var builder = StringBuilder(prefix: "", separator: " ")
builder.append(stringReprOf(head))
var expr = tail
while case .pair(let car, let cdr) = expr {
builder.append(stringReprOf(car))
expr = cdr
}
res += (builder.description + (expr.isNull ? "" : " . \(stringReprOf(expr))"))
.truncated(limit: 100)
default:
res += stringReprOf(expr).truncated(limit: 100)
}
return res + ">"
case .tagged(let tag, let expr):
if case .object(let objTag) = tag {
if case .object(let objExpr) = expr {
return "#<\(objTag.tagString): \(objExpr.tagString)>"
} else {
return "#<\(objTag.tagString): \(stringReprOf(expr))>"
}
} else if case .object(let objExpr) = expr {
return "#<tag \(stringReprOf(tag)): \(objExpr.tagString)>"
} else {
return "#<tag \(stringReprOf(tag)): \(stringReprOf(expr))>"
}
case .error(let error):
return "#<\(error.inlineDescription)>"
case .syntax(_, let expr):
return stringReprOf(expr)
}
}
return stringReprOf(self)
}
internal static func escapeStr(_ str: String) -> String {
var res = ""
for c in str {
switch c {
case "\u{7}": res += "\\a"
case "\u{8}": res += "\\b"
case "\t": res += "\\t"
case "\n": res += "\\n"
case "\u{11}": res += "\\v"
case "\u{12}": res += "\\f"
case "\r": res += "\\r"
case "\"": res += "\\\""
case "\\": res += "\\\\"
default: res.append(c)
}
}
return res
}
public static func ==(lhs: Expr, rhs: Expr) -> Bool {
return equalExpr(rhs, lhs)
}
}
public typealias ByteVector = MutableBox<[UInt8]>
public typealias DoubleComplex = ImmutableBox<Complex<Double>>
| 348e4f9f3c944f1cb4cf70a40617984a | 30.094634 | 100 | 0.548695 | false | false | false | false |
rwbutler/TypographyKit | refs/heads/master | Example/TypographyKit/MenuViewController.swift | mit | 1 | //
// MenuViewController.swift
// TypographyKit
//
// Created by Ross Butler on 22/02/2020.
// Copyright © 2020 Ross Butler. All rights reserved.
//
import Foundation
import UIKit
import TypographyKit
class MenuViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "TypographyKit"
}
@IBAction func presentTypographyColors(_ sender: UIButton) {
if #available(iOS 9.0, *), let navController = navigationController {
let navSettings = ViewControllerNavigationSettings(animated: true,
closeButtonAlignment: .noCloseButtonExportButtonRight)
TypographyKit.pushTypographyColors(navigationController: navController, navigationSettings: navSettings)
}
}
@IBAction func presentTypographyStyles(_ sender: UIButton) {
if let navController = navigationController {
let navSettings = ViewControllerNavigationSettings(animated: true,
closeButtonAlignment: .noCloseButtonExportButtonRight)
TypographyKit.pushTypographyStyles(navigationController: navController, navigationSettings: navSettings)
}
}
}
| cf9363d98eb881b10ad8b7a5bfaed9bd | 34.555556 | 117 | 0.657031 | false | false | false | false |
PiXeL16/RxViewModel | refs/heads/master | Carthage/Checkouts/RxSwift/RxCocoa/iOS/UITableView+Rx.swift | gpl-3.0 | 18 | //
// UITableView+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 4/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
import UIKit
// Items
extension UITableView {
/**
Binds sequences of elements to table view rows.
- parameter source: Observable sequence of items.
- parameter cellFactory: Transform between sequence elements and view cells.
- returns: Disposable object that can be used to unbind.
*/
public func rx_itemsWithCellFactory<S: SequenceType, O: ObservableType where O.E == S>
(source: O)
(cellFactory: (UITableView, Int, S.Generator.Element) -> UITableViewCell)
-> Disposable {
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S>(cellFactory: cellFactory)
return self.rx_itemsWithDataSource(dataSource)(source: source)
}
/**
Binds sequences of elements to table view rows.
- parameter cellIdentifier: Identifier used to dequeue cells.
- parameter source: Observable sequence of items.
- parameter configureCell: Transform between sequence elements and view cells.
- parameter cellType: Type of table view cell.
- returns: Disposable object that can be used to unbind.
*/
public func rx_itemsWithCellIdentifier<S: SequenceType, Cell: UITableViewCell, O : ObservableType where O.E == S>
(cellIdentifier: String, cellType: Cell.Type = Cell.self)
(source: O)
(configureCell: (Int, S.Generator.Element, Cell) -> Void)
-> Disposable {
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S> { (tv, i, item) in
let indexPath = NSIndexPath(forItem: i, inSection: 0)
let cell = tv.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! Cell
configureCell(i, item, cell)
return cell
}
return self.rx_itemsWithDataSource(dataSource)(source: source)
}
/**
Binds sequences of elements to table view rows using a custom reactive data used to perform the transformation.
- parameter dataSource: Data source used to transform elements to view cells.
- parameter source: Observable sequence of items.
- returns: Disposable object that can be used to unbind.
*/
public func rx_itemsWithDataSource<DataSource: protocol<RxTableViewDataSourceType, UITableViewDataSource>, S: SequenceType, O: ObservableType where DataSource.Element == S, O.E == S>
(dataSource: DataSource)
(source: O)
-> Disposable {
return source.subscribeProxyDataSourceForObject(self, dataSource: dataSource, retainDataSource: false) { [weak self] (_: RxTableViewDataSourceProxy, event) -> Void in
guard let tableView = self else {
return
}
dataSource.tableView(tableView, observedEvent: event)
}
}
}
extension UITableView {
/**
Factory method that enables subclasses to implement their own `rx_delegate`.
- returns: Instance of delegate proxy that wraps `delegate`.
*/
public override func rx_createDelegateProxy() -> RxScrollViewDelegateProxy {
return RxTableViewDelegateProxy(parentObject: self)
}
/**
Factory method that enables subclasses to implement their own `rx_dataSource`.
- returns: Instance of delegate proxy that wraps `dataSource`.
*/
public func rx_createDataSourceProxy() -> RxTableViewDataSourceProxy {
return RxTableViewDataSourceProxy(parentObject: self)
}
/**
Reactive wrapper for `dataSource`.
For more information take a look at `DelegateProxyType` protocol documentation.
*/
public var rx_dataSource: DelegateProxy {
return proxyForObject(RxTableViewDataSourceProxy.self, self)
}
/**
Installs data source as forwarding delegate on `rx_dataSource`.
It enables using normal delegate mechanism with reactive delegate mechanism.
- parameter dataSource: Data source object.
- returns: Disposable object that can be used to unbind the data source.
*/
public func rx_setDataSource(dataSource: UITableViewDataSource)
-> Disposable {
let proxy = proxyForObject(RxTableViewDataSourceProxy.self, self)
return installDelegate(proxy, delegate: dataSource, retainDelegate: false, onProxyForObject: self)
}
// events
/**
Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`.
*/
public var rx_itemSelected: ControlEvent<NSIndexPath> {
let source = rx_delegate.observe("tableView:didSelectRowAtIndexPath:")
.map { a in
return a[1] as! NSIndexPath
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`.
*/
public var rx_itemDeselected: ControlEvent<NSIndexPath> {
let source = rx_delegate.observe("tableView:didDeselectRowAtIndexPath:")
.map { a in
return a[1] as! NSIndexPath
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
*/
public var rx_itemInserted: ControlEvent<NSIndexPath> {
let source = rx_dataSource.observe("tableView:commitEditingStyle:forRowAtIndexPath:")
.filter { a in
return UITableViewCellEditingStyle(rawValue: (a[1] as! NSNumber).integerValue) == .Insert
}
.map { a in
return (a[2] as! NSIndexPath)
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
*/
public var rx_itemDeleted: ControlEvent<NSIndexPath> {
let source = rx_dataSource.observe("tableView:commitEditingStyle:forRowAtIndexPath:")
.filter { a in
return UITableViewCellEditingStyle(rawValue: (a[1] as! NSNumber).integerValue) == .Delete
}
.map { a in
return (a[2] as! NSIndexPath)
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:moveRowAtIndexPath:toIndexPath:`.
*/
public var rx_itemMoved: ControlEvent<ItemMovedEvent> {
let source: Observable<ItemMovedEvent> = rx_dataSource.observe("tableView:moveRowAtIndexPath:toIndexPath:")
.map { a in
return ((a[1] as! NSIndexPath), (a[2] as! NSIndexPath))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`.
It can be only used when one of the `rx_itemsWith*` methods is used to bind observable sequence,
or any other data source conforming to `SectionedViewDataSourceType` protocol.
```
tableView.rx_modelSelected(MyModel.self)
.map { ...
```
*/
public func rx_modelSelected<T>(modelType: T.Type) -> ControlEvent<T> {
let source: Observable<T> = rx_itemSelected.flatMap { [weak self] indexPath -> Observable<T> in
guard let view = self else {
return Observable.empty()
}
return Observable.just(try view.rx_modelAtIndexPath(indexPath))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`.
It can be only used when one of the `rx_itemsWith*` methods is used to bind observable sequence,
or any other data source conforming to `SectionedViewDataSourceType` protocol.
```
tableView.rx_modelDeselected(MyModel.self)
.map { ...
```
*/
public func rx_modelDeselected<T>(modelType: T.Type) -> ControlEvent<T> {
let source: Observable<T> = rx_itemDeselected.flatMap { [weak self] indexPath -> Observable<T> in
guard let view = self else {
return Observable.empty()
}
return Observable.just(try view.rx_modelAtIndexPath(indexPath))
}
return ControlEvent(events: source)
}
/**
Synchronous helper method for retrieving a model at indexPath through a reactive data source.
*/
public func rx_modelAtIndexPath<T>(indexPath: NSIndexPath) throws -> T {
let dataSource: SectionedViewDataSourceType = castOrFatalError(self.rx_dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx_items*` methods was used.")
let element = try dataSource.modelAtIndexPath(indexPath)
return element as! T
}
}
#endif
#if os(tvOS)
extension UITableView {
/**
Reactive wrapper for `delegate` message `tableView:didUpdateFocusInContext:withAnimationCoordinator:`.
*/
public var rx_didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UIFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> {
let source = rx_delegate.observe("tableView:didUpdateFocusInContext:withAnimationCoordinator:")
.map { a -> (context: UIFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in
let context = a[1] as! UIFocusUpdateContext
let animationCoordinator = a[2] as! UIFocusAnimationCoordinator
return (context: context, animationCoordinator: animationCoordinator)
}
return ControlEvent(events: source)
}
}
#endif
| 89a2f28865070cd2eb0789aaca1f3d98 | 35.477941 | 194 | 0.651885 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio | refs/heads/master | uoregon-cis-399/examples/LendingLibrary/LendingLibrary/Source/Controller/CategoryDetailViewController.swift | gpl-3.0 | 1 | //
// CategoryDetailViewController.swift
// LendingLibrary
//
// Created by Charles Augustine.
//
//
import UIKit
class CategoryDetailViewController: UITableViewController, UITextFieldDelegate {
// MARK: IBAction
@IBAction private func cancel(_ sender: AnyObject) {
delegate.categoryDetailViewControllerDidFinish(self)
}
@IBAction private func save(_ sender: AnyObject) {
let orderIndex = delegate.numberOfCategoriesForCategoryDetailViewController(self)
do {
try LendingLibraryService.shared.addCategory(withName: name, andOrderIndex: orderIndex)
delegate.categoryDetailViewControllerDidFinish(self)
}
catch _ {
let alertController = UIAlertController(title: "Save failed", message: "Failed to save the new lent item", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
}
// MARK: UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
nameTextField.becomeFirstResponder()
}
// MARK: UITextFieldDelegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
name = ((textField.text ?? "") as NSString).replacingCharacters(in: range, with: string)
return true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
nameTextField.resignFirstResponder()
return false
}
// MARK: View Management
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if selectedCategory != nil {
navigationItem.title = "Edit Category"
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
}
else {
navigationItem.title = "Add Category"
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(CategoryDetailViewController.cancel(_:)))
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(CategoryDetailViewController.save(_:)))
}
nameTextField.text = name
}
override func viewWillDisappear(_ animated: Bool) {
if let someCategory = selectedCategory {
do {
try LendingLibraryService.shared.renameCategory(someCategory, withNewName: name)
}
catch _ {
let alertController = UIAlertController(title: "Save failed", message: "Failed to save the new lent item", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
}
super.viewWillDisappear(animated)
}
// MARK: Properties
var selectedCategory: Category? {
didSet {
if let someCategory = selectedCategory {
name = someCategory.name!
}
else {
name = CategoryDetailViewController.defaultName
}
}
}
var delegate: CategoryDetailViewControllerDelegate!
// MARK: Properties (Private)
private var name = CategoryDetailViewController.defaultName
// MARK: Properties (IBOutlet)
@IBOutlet private weak var nameTextField: UITextField!
// MARK: Properties (Private Static Constant)
private static let defaultName = "New Category"
}
| ad4f5038562cb6dd19d5a33893dbb685 | 29.59633 | 157 | 0.753823 | false | false | false | false |
maurovc/MyMarvel | refs/heads/master | MyMarvel/NoDataCollectionViewCell.swift | mit | 1 | //
// NoDataCollectionViewCell.swift
// MyMarvel
//
// Created by Mauro Vime Castillo on 27/10/16.
// Copyright © 2016 Mauro Vime Castillo. All rights reserved.
//
import UIKit
/**
SadCharacters is an enumeration used represent the different "no data cell" options. This class uses famous Marvel charcters to represent the data.
- Deadpool
- Cyclops
- Wolverine
- Daredevil
*/
enum SadCharacters: Int {
case Deadpool = 0
case Cyclops = 1
case Wolverine = 2
case Daredevil = 3
func imageName() -> String {
switch self {
case .Deadpool: return "sadDeadpool"
case .Cyclops: return "sadCyclops"
case .Wolverine: return "sadWolverine"
case .Daredevil: return "sadDaredevil"
}
}
func description() -> String {
switch self {
case .Deadpool: return NSLocalizedString("I'm sorry! This character doesn't appear in any comic", comment: "")
case .Cyclops: return NSLocalizedString("I'm sorry! This character doesn't have any serie", comment: "")
case .Wolverine: return NSLocalizedString("I'm sorry! This character doesn't have any event", comment: "")
case .Daredevil: return NSLocalizedString("I'm sorry! This character doesn't have any story", comment: "")
}
}
}
/// Class that represents a cell used to display that a CollectionView doesn't have data.
class NoDataCollectionViewCell: UICollectionViewCell {
static let identifier = "noDataCell"
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var logoImageView: UIImageView!
var type: SadCharacters? {
didSet {
descriptionLabel.text = type?.description()
logoImageView.image = UIImage(named: type?.imageName() ?? "")
}
}
}
| 3b91f946bac2d3c94d4b93c8e828e8e3 | 29.779661 | 148 | 0.654736 | false | false | false | false |
andrucuna/ios | refs/heads/master | Swiftris/Swiftris/Shape.swift | gpl-2.0 | 1 | //
// Shape.swift
// Swiftris
//
// Created by Andrés Ruiz on 9/25/14.
// Copyright (c) 2014 Andrés Ruiz. All rights reserved.
//
import Foundation
import SpriteKit
let NumOrientations: UInt32 = 4
enum Orientation: Int, Printable
{
case Zero = 0, Ninety, OneEighty, TwoSeventy
var description: String
{
switch self
{
case .Zero:
return "0"
case .Ninety:
return "90"
case .OneEighty:
return "180"
case .TwoSeventy:
return "270"
}
}
static func random() -> Orientation
{
return Orientation.fromRaw(Int(arc4random_uniform(NumOrientations)))!
}
// We provided a method capable of returning the next orientation when traveling either clockwise or
// counterclockwise.
static func rotate(orientation:Orientation, clockwise: Bool) -> Orientation
{
var rotated = orientation.toRaw() + (clockwise ? 1 : -1)
if rotated > Orientation.TwoSeventy.toRaw()
{
rotated = Orientation.Zero.toRaw()
}
else if rotated < 0
{
rotated = Orientation.TwoSeventy.toRaw()
}
return Orientation.fromRaw(rotated)!
}
}
// The number of total shape varieties
let NumShapeTypes: UInt32 = 7
// Shape indexes
let FirstBlockIdx: Int = 0
let SecondBlockIdx: Int = 1
let ThirdBlockIdx: Int = 2
let FourthBlockIdx: Int = 3
class Shape: Hashable, Printable {
// The color of the shape
let color:BlockColor
// The blocks comprising the shape
var blocks = Array<Block>()
// The current orientation of the shape
var orientation: Orientation
// The column and row representing the shape's anchor point
var column, row:Int
// Required Overrides
// Defines a computed Dictionary. A dictionary is defined with square braces – […] – and maps one type
// of object to another.
// Subclasses must override this property
var blockRowColumnPositions: [Orientation: Array<(columnDiff: Int, rowDiff: Int)>] {
return [:]
}
// #2
// Subclasses must override this property
var bottomBlocksForOrientations: [Orientation: Array<Block>] {
return [:]
}
// We wrote a complete computed property which is designed to return the bottom blocks of the shape at
// its current orientation. This will be useful later when our blocks get physical and start contacting
// walls and each other.
var bottomBlocks:Array<Block>
{
if let bottomBlocks = bottomBlocksForOrientations[orientation]
{
return bottomBlocks
}
return []
}
// Hashable
var hashValue:Int
{
// We use the reduce<S : Sequence, U>(sequence: S, initial: U, combine: (U, S.GeneratorType.Element)
// -> U) -> U method to iterate through our entire blocks array. We exclusively-or each block's
// hashValue together to create a single hashValue for the Shape they comprise.
return reduce(blocks, 0) { $0.hashValue ^ $1.hashValue }
}
// Printable
var description: String
{
return "\(color) block facing \(orientation): \(blocks[FirstBlockIdx]), \(blocks[SecondBlockIdx]), \(blocks[ThirdBlockIdx]), \(blocks[FourthBlockIdx])"
}
init( column:Int, row:Int, color: BlockColor, orientation:Orientation )
{
self.color = color
self.column = column
self.row = row
self.orientation = orientation
initializeBlocks()
}
// We introduce a special type of initializer. A convenience initializer must call down to a standard
// initializer or otherwise your class will fail to compile. We've placed this one here in order to
// simplify the initialization process for users of the Shape class. It assigns the given row and column
// values while generating a random color and a random orientation.
convenience init(column:Int, row:Int)
{
self.init(column:column, row:row, color:BlockColor.random(), orientation:Orientation.random())
}
// We defined a final function which means it cannot be overridden by subclasses. This implementation of
// initializeBlocks() is the only one allowed by Shape and its subclasses.
final func initializeBlocks()
{
// We introduced conditional assignments. This if conditional first attempts to assign an array into
// blockRowColumnTranslations after extracting it from the computed dictionary property. If one is
// not found, the if block is not executed.
if let blockRowColumnTranslations = blockRowColumnPositions[orientation]
{
for i in 0..<blockRowColumnTranslations.count
{
let blockRow = row + blockRowColumnTranslations[i].rowDiff
let blockColumn = column + blockRowColumnTranslations[i].columnDiff
let newBlock = Block(column: blockColumn, row: blockRow, color: color)
blocks.append(newBlock)
}
}
}
final func rotateBlocks(orientation: Orientation)
{
if let blockRowColumnTranslation:Array<(columnDiff: Int, rowDiff: Int)> = blockRowColumnPositions[orientation]
{
// We introduce the enumerate operator. This allows us to iterate through an array object by
// defining an index variable
for (idx, (columnDiff:Int, rowDiff:Int)) in enumerate(blockRowColumnTranslation)
{
blocks[idx].column = column + columnDiff
blocks[idx].row = row + rowDiff
}
}
}
// We created a couple methods for quickly rotating a shape one turn clockwise or counterclockwise, this
// will come in handy when testing a potential rotation and reverting it if it breaks the rules. Below
//that we've added convenience functions which allow us to move our shapes incrementally in any direction.
final func rotateClockwise()
{
let newOrientation = Orientation.rotate(orientation, clockwise: true)
rotateBlocks(newOrientation)
orientation = newOrientation
}
final func rotateCounterClockwise()
{
let newOrientation = Orientation.rotate(orientation, clockwise: false)
rotateBlocks(newOrientation)
orientation = newOrientation
}
final func lowerShapeByOneRow()
{
shiftBy(0, rows:1)
}
final func raiseShapeByOneRow()
{
shiftBy(0, rows:-1)
}
final func shiftRightByOneColumn()
{
shiftBy(1, rows:0)
}
final func shiftLeftByOneColumn()
{
shiftBy(-1, rows:0)
}
// We've included a simple shiftBy(columns: Int, rows: Int) method which will adjust each row and column
// by rows and columns, respectively.
final func shiftBy(columns: Int, rows: Int)
{
self.column += columns
self.row += rows
for block in blocks
{
block.column += columns
block.row += rows
}
}
// We provide an absolute approach to position modification by setting the column and row properties
// before rotating the blocks to their current orientation which causes an accurate realignment of all
// blocks relative to the new row and column properties.
final func moveTo(column: Int, row:Int)
{
self.column = column
self.row = row
rotateBlocks(orientation)
}
final class func random(startingColumn:Int, startingRow:Int) -> Shape
{
switch Int(arc4random_uniform(NumShapeTypes))
{
// We've created a method to generate a random Tetromino shape and you can see that subclasses
// naturally inherit initializers from their parent class.
case 0:
return SquareShape(column:startingColumn, row:startingRow)
case 1:
return LineShape(column:startingColumn, row:startingRow)
case 2:
return TShape(column:startingColumn, row:startingRow)
case 3:
return LShape(column:startingColumn, row:startingRow)
case 4:
return JShape(column:startingColumn, row:startingRow)
case 5:
return SShape(column:startingColumn, row:startingRow)
default:
return ZShape(column:startingColumn, row:startingRow)
}
}
}
func ==(lhs: Shape, rhs: Shape) -> Bool
{
return lhs.row == rhs.row && lhs.column == rhs.column
}
| 2b30a4f5841b96d15b08b51e244dffad | 33.255906 | 159 | 0.630732 | false | false | false | false |
Harley-xk/Chrysan | refs/heads/master | Example/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Example
//
// Created by Harley-xk on 2020/6/1.
// Copyright © 2020 Harley. All rights reserved.
//
import UIKit
import Chrysan
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let options = HUDResponder.global.viewOptions
options.mainColor = .systemRed
var maskColor = UIColor.black.withAlphaComponent(0.2)
if #available(iOS 13.0, *) {
maskColor = UIColor.label.withAlphaComponent(0.2)
}
options.maskColor = maskColor
options.hudVisualEffect = UIBlurEffect(style: .prominent)
options.hudCornerRadius = 10
HUDResponder.global.register(.circleDots, for: .loading)
return true
}
}
| 297601884de1042b0dc54d325ef5ea05 | 26.75 | 145 | 0.677678 | false | false | false | false |
caiobzen/Pomodoro | refs/heads/master | Pomodoro/CCCoreDataStack.swift | mit | 1 | //
// CCCoreDataStack.swift
// Pomodoro
//
// Created by Carlos Corrêa on 8/25/15.
// Copyright © 2015 Carlos Corrêa. All rights reserved.
//
import Foundation
import CoreData
public class CCCoreDataStack {
public class var sharedInstance:CCCoreDataStack {
struct Singleton {
static let instance = CCCoreDataStack()
}
return Singleton.instance
}
// MARK: - CRUD methods
/**
This method will add a new TaskModel object into core data.
:param: name The given name of the TaskModel object.
:returns: A brand new TaskModel object.
*/
public func createTask(name:String) -> TaskModel? {
let newTask = NSEntityDescription.insertNewObjectForEntityForName("TaskModel", inManagedObjectContext: self.managedObjectContext!) as! TaskModel;
newTask.name = name
newTask.creationTime = NSDate()
return newTask
}
/**
This method will delete a TaskModel object from core data.
:param: task The given TaskModel object to be deleted.
*/
public func deleteTask(task:TaskModel) {
self.managedObjectContext?.deleteObject(task)
self.saveContext()
}
/**
This method will fetch all the TaskModel objects from core data.
:returns: An Array of TaskModel objects.
*/
public func allTasks() -> [TaskModel]? {
let request = NSFetchRequest(entityName: "TaskModel")
request.sortDescriptors = [
NSSortDescriptor(key: "creationTime", ascending: false)
]
do {
let tasks = try self.managedObjectContext?.executeFetchRequest(request) as! [TaskModel]?
return tasks
} catch let error as NSError {
print(error)
return []
}
}
// MARK: - lazy vars
//Why lazy vars? For delaying the creation of an object or some other expensive process until it’s needed. And we can also add logic to our lazy initialization. That is cool, huh?
lazy var applicationDocumentsDirectory: NSURL = {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
// The managed object model for the application.
lazy var managedObjectModel: NSManagedObjectModel = {
return NSManagedObjectModel.mergedModelFromBundles(nil)!
}()
// The persistent store coordinator for the application.
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
var containerPath = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Pomodoro.sqlite")
var error: NSError? = nil
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: containerPath, options: nil)
} catch {
return nil
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
public func saveContext () {
if let context = self.managedObjectContext {
if (context.hasChanges) {
do{
try context.save()
} catch let error as NSError {
print(error)
}
}
}
}
} | 413deb1143f982211c9ef9f36422a0fa | 32.842105 | 183 | 0.65232 | false | false | false | false |
RickiG/dynamicCellHeight | refs/heads/master | AutolayoutCellPoC/TextCell.swift | mit | 1 | //
// BasicCell.swift
// AutolayoutCellPoC
//
// Created by Ricki Gregersen on 05/12/14.
// Copyright (c) 2014 youandthegang.com. All rights reserved.
//
import UIKit
class TextCell: SizeableTableViewCell, SizeableCell, UpdateableCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subTitleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func layoutSubviews() {
super.layoutSubviews()
self.contentView.layoutIfNeeded()
updatePreferredLayoutSizes()
}
/*
Method : updatePreferredLayoutSizes()
The preferredMaxLayoutWidth must be reset
on each layout for the dynamic sizing to work
*/
func updatePreferredLayoutSizes() {
titleLabel.preferredMaxLayoutWidth = CGRectGetWidth(titleLabel.frame)
subTitleLabel.preferredMaxLayoutWidth = CGRectGetWidth(subTitleLabel.frame)
}
func update(data: AnyObject) {
if let d = data as? CellTextData {
titleLabel.text = d.title
subTitleLabel.text = d.subTitle
}
}
}
| e88835e2efa8470f596647bff1583ef8 | 26.095238 | 83 | 0.672232 | false | false | false | false |
snewolnivekios/HideNavTabBarsDemo | refs/heads/master | HideNavTabBarsDemo/BarsSettingsViewController.swift | gpl-3.0 | 1 | //
// BarsSettingsViewController.swift
// HideNavTabBarsDemo
//
// Copyright © 2016 Kevin L. Owens. All rights reserved.
//
// HideNavTabBarsDemo 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.
//
// HideNavTabBarsDemo 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 HideNavTabBarsDemo. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
/// Presents the table view controller-based settings view for navigation and tab bar animations.
class BarsSettingsViewController: UITableViewController {
/// The data containing switch-configurable navigation and tab bar animation settings.
var barsSettingsModel = BarsSettingsModel(id: "\(#file)")
/// Configures cell heights to adjust to autosizing subviews (where Lines is set to 0).
override func viewDidLoad() {
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 42
}
/// Shows the navigation bar.
override func viewWillAppear(_ animated: Bool) {
navigationController?.setNavigationBarHidden(false, animated: true)
}
/// Returns the number of settings groups.
override func numberOfSections(in tableView: UITableView) -> Int {
return barsSettingsModel.numberOfSections
}
/// Returns the number of configuration items in the given `section`.
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return barsSettingsModel.numberOfRows(inSection: section)
}
/// Returns a cell populated with `barsSettings`-provided data corresponding to the given `indexPath`.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LabelDetailSwitch") as! LabelDetailSwitchCell
if let content = barsSettingsModel.content(for: indexPath) {
cell.label.text = content.label
cell.label.sizeToFit()
cell.detail.text = content.detail
cell.switch.isOn = content.isOn
cell.switch.tag = indexPath.section * 100 + indexPath.row
cell.switch.addTarget(self, action: #selector(BarsSettingsViewController.switchValueChanged(sender:)), for: .valueChanged)
}
return cell
}
/// Updates the `barsSettings` with the setting corresponding do the given `sender` switch.
func switchValueChanged(sender: UISwitch) {
let section = sender.tag / 100
let row = sender.tag - section
barsSettingsModel.set(isOn: sender.isOn, for: IndexPath(row: row, section: section))
}
}
| 366835d5e6581f3dc1b00731557030df | 38.105263 | 128 | 0.74428 | false | false | false | false |
adevelopers/prosvet | refs/heads/master | Prosvet/Common/Controllers/MainVC.swift | mit | 1 | //
// ViewController.swift
// Prosvet
//
// Created by adeveloper on 17.04.17.
// Copyright © 2017 adeveloper. All rights reserved.
//
import UIKit
class MainVC: UIViewController {
@IBOutlet weak var uiTable: UITableView!
var posts:[Post] = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
loadFeedFromServer()
}
func loadFeedFromServer(){
let model = NetModel()
model.npGetList({
posts in
DispatchQueue.main.async {
self.posts = posts
self.uiTable.reloadData()
}
})
}
}
// MARK: - Constants
extension MainVC {
fileprivate struct Constants {
static let postCellIdentifier = "PostCell"
static let postSegueIdentifier = "segueShowPost"
}
}
//MARK: DataSource
extension MainVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("MainCell", owner: self, options: nil)?.first as! MainCell
let title = posts[indexPath.row].title
cell.uiTitle.text = title
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80.0
}
}
// MARK: - UITableViewDelegate
extension MainVC: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
performSegue(withIdentifier: Constants.postSegueIdentifier, sender: posts[indexPath.row])
}
}
// MARK: - Segue
extension MainVC {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == Constants.postSegueIdentifier {
let controller = segue.destination as! PostDetail
let post = sender as! Post
controller.post = post
}
}
}
| 8af4d3d871078f82f57f533a90dc722f | 22.695652 | 110 | 0.618349 | false | false | false | false |
lapcat/vienna-rss | refs/heads/master | Carthage/Checkouts/Sparkle/generate_appcast/FeedXML.swift | apache-2.0 | 1 | //
// Created by Kornel on 22/12/2016.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
import Foundation
let maxVersionsInFeed = 5;
func findElement(name: String, parent: XMLElement) -> XMLElement? {
if let found = try? parent.nodes(forXPath: name) {
if found.count > 0 {
if let element = found[0] as? XMLElement {
return element;
}
}
}
return nil;
}
func findOrCreateElement(name: String, parent: XMLElement) -> XMLElement {
if let element = findElement(name: name, parent: parent) {
return element;
}
let element = XMLElement(name: name);
linebreak(parent);
parent.addChild(element);
return element;
}
func text(_ text: String) -> XMLNode {
return XMLNode.text(withStringValue: text) as! XMLNode
}
func linebreak(_ element: XMLElement) {
element.addChild(text("\n"));
}
func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem]) throws {
let appBaseName = updates[0].appPath.deletingPathExtension().lastPathComponent;
let sparkleNS = "http://www.andymatuschak.org/xml-namespaces/sparkle";
var doc: XMLDocument;
do {
let options: XMLNode.Options = [
XMLNode.Options.nodeLoadExternalEntitiesNever,
XMLNode.Options.nodePreserveCDATA,
XMLNode.Options.nodePreserveWhitespace,
];
doc = try XMLDocument(contentsOf: appcastDestPath, options: options);
} catch {
let root = XMLElement(name: "rss");
root.addAttribute(XMLNode.attribute(withName: "xmlns:sparkle", stringValue: sparkleNS) as! XMLNode);
root.addAttribute(XMLNode.attribute(withName: "version", stringValue: "2.0") as! XMLNode);
doc = XMLDocument(rootElement: root);
doc.isStandalone = true;
}
var channel: XMLElement;
let rootNodes = try doc.nodes(forXPath: "/rss");
if rootNodes.count != 1 {
throw makeError(code: .appcastError, "Weird XML? \(appcastDestPath.path)");
}
let root = rootNodes[0] as! XMLElement
let channelNodes = try root.nodes(forXPath: "channel");
if channelNodes.count > 0 {
channel = channelNodes[0] as! XMLElement;
} else {
channel = XMLElement(name: "channel");
linebreak(channel);
channel.addChild(XMLElement.element(withName: "title", stringValue: appBaseName) as! XMLElement);
linebreak(root);
root.addChild(channel);
}
var numItems = 0;
for update in updates {
var item: XMLElement;
let existingItems = try channel.nodes(forXPath: "item[enclosure[@sparkle:version=\"\(update.version)\"]]");
let createNewItem = existingItems.count == 0;
// Update all old items, but aim for less than 5 in new feeds
if createNewItem && numItems >= maxVersionsInFeed {
continue;
}
numItems += 1;
if createNewItem {
item = XMLElement.element(withName: "item") as! XMLElement;
linebreak(channel);
channel.addChild(item);
} else {
item = existingItems[0] as! XMLElement;
}
if nil == findElement(name: "title", parent: item) {
linebreak(item);
item.addChild(XMLElement.element(withName: "title", stringValue: update.shortVersion) as! XMLElement);
}
if nil == findElement(name: "pubDate", parent: item) {
linebreak(item);
item.addChild(XMLElement.element(withName: "pubDate", stringValue: update.pubDate) as! XMLElement);
}
if let html = update.releaseNotesHTML {
let descElement = findOrCreateElement(name: "description", parent: item);
let cdata = XMLNode(kind:.text, options:.nodeIsCDATA);
cdata.stringValue = html;
descElement.setChildren([cdata]);
}
var minVer = findElement(name: "sparkle:minimumSystemVersion", parent: item);
if nil == minVer {
minVer = XMLElement.element(withName: "sparkle:minimumSystemVersion", uri: sparkleNS) as? XMLElement;
linebreak(item);
item.addChild(minVer!);
}
minVer?.setChildren([text(update.minimumSystemVersion)]);
let relElement = findElement(name: "sparkle:releaseNotesLink", parent: item);
if let url = update.releaseNotesURL {
if nil == relElement {
linebreak(item);
item.addChild(XMLElement.element(withName:"sparkle:releaseNotesLink", stringValue: url.absoluteString) as! XMLElement);
}
} else if let childIndex = relElement?.index {
item.removeChild(at: childIndex);
}
var enclosure = findElement(name: "enclosure", parent: item);
if nil == enclosure {
enclosure = XMLElement.element(withName: "enclosure") as? XMLElement;
linebreak(item);
item.addChild(enclosure!);
}
guard let archiveURL = update.archiveURL?.absoluteString else {
throw makeError(code: .appcastError, "Bad archive name or feed URL");
};
var attributes = [
XMLNode.attribute(withName: "url", stringValue: archiveURL) as! XMLNode,
XMLNode.attribute(withName: "sparkle:version", uri: sparkleNS, stringValue: update.version) as! XMLNode,
XMLNode.attribute(withName: "sparkle:shortVersionString", uri: sparkleNS, stringValue: update.shortVersion) as! XMLNode,
XMLNode.attribute(withName: "length", stringValue: String(update.fileSize)) as! XMLNode,
XMLNode.attribute(withName: "type", stringValue: update.mimeType) as! XMLNode,
];
if let sig = update.dsaSignature {
attributes.append(XMLNode.attribute(withName: "sparkle:dsaSignature", uri: sparkleNS, stringValue: sig) as! XMLNode);
}
enclosure!.attributes = attributes;
if update.deltas.count > 0 {
var deltas = findElement(name: "sparkle:deltas", parent: item);
if nil == deltas {
deltas = XMLElement.element(withName: "sparkle:deltas", uri: sparkleNS) as? XMLElement;
linebreak(item);
item.addChild(deltas!);
} else {
deltas!.setChildren([]);
}
for delta in update.deltas {
var attributes = [
XMLNode.attribute(withName: "url", stringValue: URL(string: delta.archivePath.lastPathComponent.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed)!, relativeTo: update.archiveURL)!.absoluteString) as! XMLNode,
XMLNode.attribute(withName: "sparkle:version", uri: sparkleNS, stringValue: update.version) as! XMLNode,
XMLNode.attribute(withName: "sparkle:shortVersionString", uri: sparkleNS, stringValue: update.shortVersion) as! XMLNode,
XMLNode.attribute(withName: "sparkle:deltaFrom", uri: sparkleNS, stringValue: delta.fromVersion) as! XMLNode,
XMLNode.attribute(withName: "length", stringValue: String(delta.fileSize)) as! XMLNode,
XMLNode.attribute(withName: "type", stringValue: "application/octet-stream") as! XMLNode,
];
if let sig = delta.dsaSignature {
attributes.append(XMLNode.attribute(withName: "sparkle:dsaSignature", uri: sparkleNS, stringValue: sig) as! XMLNode);
}
linebreak(deltas!);
deltas!.addChild(XMLNode.element(withName: "enclosure", children: nil, attributes: attributes) as! XMLElement);
}
}
if createNewItem {
linebreak(item);
linebreak(channel);
}
}
let options = XMLNode.Options.nodeCompactEmptyElement;
let docData = doc.xmlData(options:options);
let _ = try XMLDocument(data: docData, options:XMLNode.Options()); // Verify that it was generated correctly, which does not always happen!
try docData.write(to: appcastDestPath);
}
| 2a3cb698f1491df2f4cf973c8b71407c | 41.552632 | 252 | 0.624366 | false | false | false | false |
cuba/NetworkKit | refs/heads/master | Source/Request/MultiPartRequest.swift | mit | 1 | //
// MultiPartRequest.swift
// NetworkKit iOS
//
// Created by Jacob Sikorski on 2019-03-27.
// Copyright © 2019 Jacob Sikorski. All rights reserved.
//
import Foundation
/// A convenience Request object for submitting a multi-part request.
public struct MultiPartRequest: Request {
public var method: HTTPMethod
public var path: String
public var queryItems: [URLQueryItem]
public var headers: [String: String]
public var httpBody: Data?
/// Initialize this upload request.
///
/// - Parameters:
/// - method: The HTTP method to use
/// - path: The path that will be appended to the baseURL on the `ServerProvider`.
public init(method: HTTPMethod, path: String) {
self.method = method
self.path = path
self.queryItems = []
self.headers = [:]
}
/// Set the HTTP body using multi-part form data
///
/// - Parameters:
/// - file: The file to attach. This file will be attached as-is
/// - fileName: The file name that will be used.
/// - mimeType: The mime type or otherwise known as Content-Type
/// - parameters: Any additional mult-part parameters to include
mutating public func setHTTPBody(file: Data, fileFieldName: String = "file", fileName: String, mimeType: String, parameters: [String: String] = [:]) {
let boundary = UUID().uuidString
let contentType = "multipart/form-data; boundary=\(boundary)"
let endBoundaryPart = String(format: "--%@--\r\n", boundary)
var body = makeBody(file: file, fileFieldName: fileFieldName, fileName: fileName, mimeType: mimeType, parameters: parameters, boundary: boundary)
body.append(endBoundaryPart.data(using: String.Encoding.utf8)!)
headers["Content-Length"] = "\(body.count)"
headers["Content-Type"] = contentType
self.httpBody = body
}
/// Set the HTTP body using multi-part form data
///
/// - Parameters:
/// - parameters: Any mult-part parameters to include
mutating public func setHTTPBody(parameters: [String: String]) {
let boundary = UUID().uuidString
let contentType = "multipart/form-data; boundary=\(boundary)"
let endBoundaryPart = String(format: "--%@--\r\n", boundary)
var body = makeBody(parameters: parameters, boundary: boundary)
body.append(endBoundaryPart.data(using: String.Encoding.utf8)!)
headers["Content-Length"] = "\(body.count)"
headers["Content-Type"] = contentType
self.httpBody = body
}
private func makeBody(file: Data, fileFieldName: String, fileName: String, mimeType: String, parameters: [String: String], boundary: String) -> Data {
var body = makeBody(parameters: parameters, boundary: boundary)
// Add image data
let boundaryPart = String(format: "--%@\r\n", boundary)
let keyPart = String(format: "Content-Disposition:form-data; name=\"%@\"; filename=\"%@\"\r\n", fileFieldName, fileName)
let valuePart = String(format: "Content-Type: %@\r\n\r\n", mimeType)
let spacePart = String(format: "\r\n")
body.append(boundaryPart.data(using: String.Encoding.utf8)!)
body.append(keyPart.data(using: String.Encoding.utf8)!)
body.append(valuePart.data(using: String.Encoding.utf8)!)
body.append(file)
body.append(spacePart.data(using: String.Encoding.utf8)!)
return body
}
private func makeBody(parameters: [String: String], boundary: String) -> Data {
var body = Data()
// Add params (all params are strings)
for (key, value) in parameters {
let boundaryPart = String(format: "--%@\r\n", boundary)
let keyPart = String(format: "Content-Disposition:form-data; name=\"%@\"\r\n\r\n", key)
let valuePart = String(format: "%@\r\n", value)
body.append(boundaryPart.data(using: String.Encoding.utf8)!)
body.append(keyPart.data(using: String.Encoding.utf8)!)
body.append(valuePart.data(using: String.Encoding.utf8)!)
}
return body
}
}
| 984f2528079de6647f5e677f8dc11ca9 | 41.13 | 154 | 0.626157 | false | false | false | false |
lkzhao/MCollectionView | refs/heads/master | Carthage/Checkouts/YetAnotherAnimationLibrary/Sources/Solvers/CurveSolver.swift | mit | 2 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct CurveSolver<Value: VectorConvertible>: Solver {
public let current: AnimationProperty<Value>
public let target: AnimationProperty<Value>
public let velocity: AnimationProperty<Value>
public let curve: Curve
public let duration: TimeInterval
public var start: Value.Vector
public var time: TimeInterval = 0
init(duration: TimeInterval, curve: Curve,
current: AnimationProperty<Value>,
target: AnimationProperty<Value>,
velocity: AnimationProperty<Value>) {
self.current = current
self.target = target
self.velocity = velocity
self.duration = duration
self.curve = curve
self.start = current.vector
}
public mutating func solve(dt: TimeInterval) -> Bool {
time += dt
if time > duration {
current.vector = target.vector
velocity.vector = .zero
return true
}
let t = curve.solve(time / duration)
let oldCurrent = current.vector
current.vector = (target.vector - start) * t + start
velocity.vector = (current.vector - oldCurrent) / dt
return false
}
}
| 519a325364f8598882156d93b6ae671e | 38.233333 | 80 | 0.695837 | false | false | false | false |
latera1n/Learning-Swift | refs/heads/master | TipCalc/TipCalc/ViewController.swift | mit | 1 | //
// ViewController.swift
// TipCalc
//
// Created by DengYuchi on 2/19/16.
// Copyright © 2016 LateRain. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textFieldAmount: UITextField!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var labelPercentage: UILabel! {
didSet {
labelPercentage.font = labelPercentage.font.monospacedDigitFont
}
}
@IBOutlet weak var labelTip: UILabel! {
didSet {
labelTip.font = labelTip.font.monospacedDigitFont
}
}
@IBOutlet weak var labelTotal: UILabel! {
didSet {
labelTotal.font = labelTotal.font.monospacedDigitFont
}
}
var amountString = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
slider.minimumTrackTintColor = UIColor(red: 0, green: 200/255, blue: 83/255, alpha: 1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sliderTouchedDown(sender: AnyObject) {
let textFieldAmountString = textFieldAmount.text!
if textFieldAmountString != "" && (textFieldAmountString as NSString).substringToIndex(1) != "$" && textFieldAmountString != "." {
dismissKeyboard(sender)
}
}
@IBAction func sliderValueChanged(sender: AnyObject) {
updateDisplay()
}
func updateDisplay() {
let sliderValue = slider.value
let tipPercentage = Int(sliderValue)
labelPercentage.text = String(tipPercentage) + "%"
if amountString != "" {
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .CurrencyStyle
let tip = Double(amountString)! * Double(tipPercentage) / 100
labelTip.text = numberFormatter.stringFromNumber(tip)
labelTotal.text = numberFormatter.stringFromNumber(Double(amountString)! + tip)
}
}
@IBAction func dismissKeyboard(sender: AnyObject) {
view.endEditing(true)
let textFieldAmountString = textFieldAmount.text!
if textFieldAmountString != "" && (textFieldAmountString as NSString).substringToIndex(1) != "$" && textFieldAmountString != "." {
amountString = textFieldAmount.text!
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .CurrencyStyle
textFieldAmount.text = numberFormatter.stringFromNumber(Double(amountString)!)
if textFieldAmount.text != "$0.00" {
updateDisplay()
} else {
labelTip.text = "$0.00"
labelTotal.text = "$0.00"
amountString = ""
textFieldAmount.text = ""
}
} else if textFieldAmountString == "" {
labelTip.text = "$0.00"
labelTotal.text = "$0.00"
amountString = ""
} else if textFieldAmountString == "." {
labelTip.text = "$0.00"
labelTotal.text = "$0.00"
amountString = ""
textFieldAmount.text = ""
}
}
}
| 718a6aeb15dccd6cb7a2c191a274d87a | 33.736842 | 138 | 0.603636 | false | false | false | false |
HighBay/PageMenu | refs/heads/master | Demos/Demo 1/PageMenuDemoStoryboard/PageMenuDemoStoryboard/TestCollectionViewController.swift | bsd-3-clause | 4 | //
// TestCollectionViewController.swift
// NFTopMenuController
//
// Created by Niklas Fahl on 12/17/14.
// Copyright (c) 2014 Niklas Fahl. All rights reserved.
//
import UIKit
let reuseIdentifier = "MoodCollectionViewCell"
class TestCollectionViewController: UICollectionViewController {
var moodArray : [String] = ["Relaxed", "Playful", "Happy", "Adventurous", "Wealthy", "Hungry", "Loved", "Active"]
var backgroundPhotoNameArray : [String] = ["mood1.jpg", "mood2.jpg", "mood3.jpg", "mood4.jpg", "mood5.jpg", "mood6.jpg", "mood7.jpg", "mood8.jpg"]
var photoNameArray : [String] = ["relax.png", "playful.png", "happy.png", "adventurous.png", "wealthy.png", "hungry.png", "loved.png", "active.png"]
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView!.register(UINib(nibName: "MoodCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//#warning Incomplete method implementation -- Return the number of items in the section
return 8
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : MoodCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MoodCollectionViewCell
// Configure the cell
cell.backgroundImageView.image = UIImage(named: backgroundPhotoNameArray[indexPath.row])
cell.moodTitleLabel.text = moodArray[indexPath.row]
cell.moodIconImageView.image = UIImage(named: photoNameArray[indexPath.row])
return cell
}
}
| c5ed25436eff050dff4b4f5cf71af8a1 | 41.08 | 172 | 0.701996 | false | false | false | false |
lenssss/whereAmI | refs/heads/master | Whereami/Controller/Game/GameChallengeBenameViewController.swift | mit | 1 | //
// GameChallengeBenameViewController.swift
// Whereami
//
// Created by A on 16/3/25.
// Copyright © 2016年 WuQifei. All rights reserved.
//
import UIKit
import SVProgressHUD
class GameChallengeBenameViewController: UIViewController {
var challengeLogoView:UIImageView? = nil
var tipLabel:UILabel? = nil
var nameTextField:UITextField? = nil
var gameRange:CountryModel? = nil //地区
var isRandom:Bool? = nil //是否挑战
var matchUsers:[FriendsModel]? = nil //匹配对手
override func viewDidLoad() {
super.viewDidLoad()
self.setConfig()
self.title = NSLocalizedString("challengeFriend",tableName:"Localizable", comment: "")
self.matchUsers = GameParameterManager.sharedInstance.matchUser
if self.matchUsers == nil {
GameParameterManager.sharedInstance.matchUser = [FriendsModel]()
}
self.getGameModel()
self.setUI()
// Do any additional setup after loading the view.
}
func getGameModel(){
let gameMode = GameParameterManager.sharedInstance.gameMode
let gameModel = gameMode!["competitor"] as! Int
if gameModel == Competitor.Friend.rawValue {
self.isRandom = false
}
else{
self.isRandom = true
}
}
func setUI(){
self.view.backgroundColor = UIColor.getGameColor()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("next",tableName:"Localizable", comment: ""), style: .Done, target: self, action: #selector(GameChallengeBenameViewController.pushToNextVC))
self.challengeLogoView = UIImageView()
self.challengeLogoView?.image = UIImage(named: "ChallengeLogo")
self.challengeLogoView?.contentMode = .ScaleAspectFit
self.challengeLogoView?.layer.masksToBounds = true
self.challengeLogoView?.layer.cornerRadius = 50
self.view.addSubview(self.challengeLogoView!)
self.tipLabel = UILabel()
self.tipLabel?.text = NSLocalizedString("namingChallenge",tableName:"Localizable", comment: "")
self.tipLabel?.textAlignment = .Center
self.view.addSubview(self.tipLabel!)
self.nameTextField = UITextField()
self.nameTextField?.rac_signalForControlEvents(.EditingDidEndOnExit).subscribeNext({ (textField) in
textField.resignFirstResponder()
})
self.nameTextField?.borderStyle = .RoundedRect
self.nameTextField?.backgroundColor = UIColor.whiteColor()
self.view.addSubview(self.nameTextField!)
self.challengeLogoView?.autoPinEdgeToSuperviewEdge(.Top, withInset: 60)
self.challengeLogoView?.autoSetDimensionsToSize(CGSize(width: 100,height: 100))
self.challengeLogoView?.autoAlignAxisToSuperviewAxis(.Vertical)
self.challengeLogoView?.autoPinEdge(.Bottom, toEdge: .Top, ofView: self.tipLabel!, withOffset: -50)
self.tipLabel?.autoSetDimensionsToSize(CGSize(width: 200,height: 50))
self.tipLabel?.autoAlignAxisToSuperviewAxis(.Vertical)
self.tipLabel?.autoPinEdge(.Bottom, toEdge: .Top, ofView: self.nameTextField!, withOffset: -10)
self.nameTextField?.autoPinEdgeToSuperviewEdge(.Left, withInset: 50)
self.nameTextField?.autoPinEdgeToSuperviewEdge(.Right, withInset: 50)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.rightBarButtonItem?.enabled = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func pushToNextVC(){
self.navigationItem.rightBarButtonItem?.enabled = false
let backBtn = TheBackBarButton.initWithAction({
let viewControllers = self.navigationController?.viewControllers
let index = (viewControllers?.count)! - 2
let viewController = viewControllers![index]
self.navigationController?.popToViewController(viewController, animated: true)
})
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn)
if isRandom == false {
let selectFriendVC = GameChallengeSelectFriendViewController()
GameParameterManager.sharedInstance.roomTitle = self.nameTextField?.text
self.navigationController?.pushViewController(selectFriendVC, animated: true)
}
else{
var dict = [String: AnyObject]()
dict["countryCode"] = GameParameterManager.sharedInstance.gameRange?.countryCode
dict["accountId"] = UserModel.getCurrentUser()?.id
dict["title"] = GameParameterManager.sharedInstance.roomTitle
dict["friendId"] = self.getFriendIdArray()
SocketManager.sharedInstance.sendMsg("startChangellengeFriendBattle", data: dict, onProto: "startChangellengeFriendBattleed") { (code, objs) in
if code == statusCode.Normal.rawValue{
// CoreDataManager.sharedInstance.consumeLifeItem()
print("=====================\(objs)")
self.pushVC(objs)
self.navigationItem.rightBarButtonItem?.enabled = true
}
else if code == statusCode.Error.rawValue {
self.runInMainQueue({
SVProgressHUD.showErrorWithStatus("error")
self.performSelector(#selector(self.SVProgressDismiss), withObject: nil, afterDelay: 1)
})
}
}
}
}
func pushVC(objs:[AnyObject]){
let matchDetailModel = MatchDetailModel.getModelFromDictionary(objs[0] as! [String : AnyObject])
GameParameterManager.sharedInstance.matchDetailModel = matchDetailModel
self.runInMainQueue({
let battleDetailsVC = GameChallengeBattleDetailsViewController()
self.navigationController?.pushViewController(battleDetailsVC, animated: true)
})
}
func getFriendIdArray() -> [AnyObject] {
var array = [AnyObject]()
for item in self.matchUsers! {
var dic = [String: AnyObject]()
dic["id"] = item.friendId
array.append(dic)
}
return array
}
func SVProgressDismiss(){
SVProgressHUD.dismiss()
self.backAction()
}
func backAction(){
let viewControllers = self.navigationController?.viewControllers
if viewControllers?.count != 1{
let index = (viewControllers?.count)! - 2
let viewController = viewControllers![index]
self.navigationController?.popToViewController(viewController, animated: true)
}
self.dismissViewControllerAnimated(true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 16bb4d4de7c1e7ea57602af14df6fe94 | 40.106145 | 230 | 0.64773 | false | false | false | false |
qutheory/vapor | refs/heads/master | Sources/Vapor/Middleware/FileMiddleware.swift | mit | 1 | /// Serves static files from a public directory.
///
/// `FileMiddleware` will default to `DirectoryConfig`'s working directory with `"/Public"` appended.
public final class FileMiddleware: Middleware {
/// The public directory.
/// - note: Must end with a slash.
private let publicDirectory: String
/// Creates a new `FileMiddleware`.
public init(publicDirectory: String) {
self.publicDirectory = publicDirectory.hasSuffix("/") ? publicDirectory : publicDirectory + "/"
}
/// See `Middleware`.
public func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
// make a copy of the path
var path = request.url.path
// path must be relative.
while path.hasPrefix("/") {
path = String(path.dropFirst())
}
// protect against relative paths
guard !path.contains("../") else {
return request.eventLoop.makeFailedFuture(Abort(.forbidden))
}
// create absolute file path
let filePath = self.publicDirectory + (path.removingPercentEncoding ?? path)
// check if file exists and is not a directory
var isDir: ObjCBool = false
guard FileManager.default.fileExists(atPath: filePath, isDirectory: &isDir), !isDir.boolValue else {
return next.respond(to: request)
}
// stream the file
let res = request.fileio.streamFile(at: filePath)
return request.eventLoop.makeSucceededFuture(res)
}
}
| 990f294084db457f9f9f27589cfe89db | 35.5 | 108 | 0.642531 | false | false | false | false |
justin/Aspen | refs/heads/master | Aspen/FileLogger.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2015 Justin Williams
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public final class FileLogger: NSObject, LogInterface {
public var fileURL: URL?
private var fileHandle: FileHandle?
public override init() {
super.init()
let locale = Locale(identifier: "en_US_POSIX")
let timeFormatter = DateFormatter()
timeFormatter.locale = locale
timeFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let dateString = timeFormatter.string(from: Date())
let fm = FileManager.default
let urls = fm.urls(for: .libraryDirectory, in: .userDomainMask)
guard let url = urls.last else { return }
let path = URL.init(fileURLWithPath: "\(url.path)/Logs/\(dateString).log")
fileURL = path
openFile()
}
deinit {
closeFile()
}
public func log(message: String) {
if let handle = fileHandle {
handle.seekToEndOfFile()
let messageWithNewLine = "\(message)\n"
if let data = messageWithNewLine.data(using: String.Encoding.utf8, allowLossyConversion: false) {
let exception = tryBlock {
handle.write(data)
}
if exception != nil {
print("Error writing to log file \(String(describing: exception))")
}
}
}
}
private func openFile() {
let fm = FileManager.default
if let URL = fileURL {
let filePath = URL.path
if fm.fileExists(atPath: filePath) == false {
do {
try fm.createDirectory(at: URL.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil)
} catch _ { }
fm.createFile(atPath: filePath, contents: nil, attributes: nil)
}
do {
fileHandle = try FileHandle(forWritingTo: URL)
} catch {
print("Error opening log file \(error)")
fileHandle = nil
}
}
}
private func closeFile() {
if let handle = fileHandle {
handle.closeFile()
}
fileHandle = nil
}
}
| 971aa17fa8be82c5e56b1e67bd82bbf1 | 35.531915 | 131 | 0.59901 | false | false | false | false |
theodinspire/FingerBlade | refs/heads/development | FingerBlade/TutorialViewController.swift | gpl-3.0 | 1 | //
// TutorialViewController.swift
// FingerBlade
//
// Created by Cormack on 3/3/17.
// Copyright © 2017 the Odin Spire. All rights reserved.
//
import UIKit
class TutorialViewController: UIViewController {
@IBOutlet weak var contButton: UIButton!
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var messageView: UIView!
let lefty = UserDefaults.standard.string(forKey: "Hand") == "Left"
var cut: CutLine!
var pathGenerator: CutPathGenerator!
var aniGen: AnimationGenerator!
var shapeLayer: CAShapeLayer?
var wordPath: UIBezierPath?
var wordPause: UIBezierPath?
var word: UILabel?
var dotView: UIView!
var tap: UITapGestureRecognizer!
var swipe: UITapSwipeGestureRecognizer!
var tapSwipe: UITapSwipeGestureRecognizer!
let cutStore = SampleStore()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
cut = cutStore.first
messageView.alpha = 0
messageView.layer.zPosition = 1
contButton.layer.zPosition = 2
tap = UITapGestureRecognizer(target: self, action: #selector(tapped))
tap.numberOfTapsRequired = 1
tap.numberOfTouchesRequired = 1
swipe = UITapSwipeGestureRecognizer(target: self, action: #selector(swiped))
swipe.numberOfTapsRequired = 0
swipe.numberOfTapTouchesRequired = 1
swipe.numberOfSwipeTouchesRequired = 1
tapSwipe = UITapSwipeGestureRecognizer(target: self, action: #selector(tapSwiped))
tapSwipe.numberOfTapsRequired = 1
tapSwipe.numberOfTapTouchesRequired = 1
tapSwipe.numberOfSwipeTouchesRequired = 1
contButton.isHidden = true
}
override func viewWillAppear(_ animated: Bool) {
// Path generation
pathGenerator = CutPathGenerator(ofSize: view!.bounds.size)
// Animation set up
//Touch
aniGen = AnimationGenerator(withPathGenerator: pathGenerator)
let dotDiameter = aniGen.dotSize
shapeLayer = aniGen.tapAnimation(forCut: cut)
//Words
word = UILabel()
word?.text = "Tap"
word?.sizeToFit()
word?.center = aniGen.swipeWordStartPoint(forCut: cut)
// Set up view for the touch area
let diaHalf = dotDiameter / 2
let start = pathGenerator.start(for: cut)
dotView = UIView(frame: CGRect(x: start.x - diaHalf, y: start.y - diaHalf, width: dotDiameter, height: dotDiameter))
dotView.backgroundColor = UIColor.clear
dotView.addGestureRecognizer(tap)
// Add to view
view.layer.addSublayer(shapeLayer!)
view.addSubview(dotView)
view.addSubview(word!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if let nextView = segue.destination as? CutViewController {
nextView.cutStore = cutStore
nextView.counter = 1
}
}
// Tutorial Methods
/// Handles single tap gesture
///
/// - Parameter sender: Tap Recognizer
func tapped(_ sender: UITapGestureRecognizer?) {
CATransaction.begin()
// Remove all previous animations
dotView.removeGestureRecognizer(tap)
dotView.removeFromSuperview()
word?.layer.removeAllAnimations()
word?.removeFromSuperview()
shapeLayer?.removeAllAnimations()
shapeLayer?.removeFromSuperlayer()
// Establish new animations
word = UILabel()
word?.text = "Swipe"
word?.sizeToFit()
word?.center = aniGen.swipeWordRestPoint(forCut: cut)
word?.layer.add(aniGen.wordSwipeAnimation(forCut: cut), forKey: "position")
shapeLayer = aniGen.swipeAnimation(forCut: cut)
view.layer.addSublayer(shapeLayer!)
view.addSubview(word!)
view.addGestureRecognizer(swipe)
CATransaction.commit()
}
/// Handles the solitary swipe gesture
///
/// - Parameter sender: Swipe recognizer
func swiped(_ sender: UITapSwipeGestureRecognizer) {
CATransaction.begin()
// Remove all previous animations
view.removeGestureRecognizer(swipe)
word?.layer.removeAllAnimations()
word?.removeFromSuperview()
shapeLayer?.removeAllAnimations()
shapeLayer?.removeFromSuperlayer()
// Establish new animations
word = UILabel()
word?.numberOfLines = 0
word?.textAlignment = .center
word?.text = "Tap and\nSwipe"
word?.sizeToFit()
word?.center = aniGen.swipeWordRestPoint(forCut: cut)
word?.layer.add(aniGen.wordSwipeAnimation(forCut: cut, long: true), forKey: "position")
shapeLayer = aniGen.tapSwipeAnimation(forCut: cut)
view.layer.addSublayer(shapeLayer!)
view.addSubview(word!)
view.addGestureRecognizer(tapSwipe)
CATransaction.commit()
}
/// Handles the Tap and Swipe recognizer
///
/// - Parameter sender: TapSwipe recognizer
func tapSwiped(_ sender: UITapSwipeGestureRecognizer) {
view.removeGestureRecognizer(tapSwipe)
CATransaction.begin()
shapeLayer?.removeAllAnimations()
shapeLayer?.removeFromSuperlayer()
word?.layer.removeAllAnimations()
word?.removeFromSuperview()
CATransaction.commit()
// Message animations
contButton.alpha = 0
contButton.isHidden = false
messageLabel.text = "You got it!"
let animateIn = { self.messageView.alpha = 1; self.contButton.alpha = 1 }
let options: UIViewAnimationOptions = [.curveEaseInOut, .beginFromCurrentState]
UIView.animate(withDuration: 0.5, delay: 0, options: options, animations: animateIn, completion: nil)
// Prepare
cutStore.put(trail: sender.trail, into: cut)
}
}
| 4c7132e7e44a35d3de372df487acfac2 | 31.79602 | 124 | 0.630309 | false | false | false | false |
blackspotbear/MMDViewer | refs/heads/master | MMDViewer/DataReader.swift | mit | 1 | import Foundation
class DataReader {
var defaultEncoding = String.Encoding.utf16LittleEndian
var data: Data
var pointer: UnsafeRawPointer
init(data: Data) {
self.data = data
pointer = (data as NSData).bytes
}
func read<T>() -> T {
let t = pointer.assumingMemoryBound(to: T.self)
pointer = UnsafeRawPointer(t.successor())
return t.pointee
}
func readIntN(_ n: Int) -> Int {
if n == 1 {
return Int(read() as UInt8)
} else if n == 2 {
return Int(read() as UInt16)
} else if n == 4 {
return Int(read() as UInt32)
} else if n == 8 {
return read()
}
return 0
}
func readString(_ encoding: UInt? = nil) -> String? {
let length = Int(read() as UInt32)
return readStringN(length, encoding: encoding)
}
func readStringN(_ nbytes: Int, encoding: UInt? = nil) -> String? {
if nbytes == 0 {
return ""
}
let r = NSString(bytes: pointer, length: nbytes, encoding: encoding ?? defaultEncoding.rawValue) as String?
pointer = pointer.advanced(by: nbytes)
return r
}
func readCStringN(_ nbytes: Int, encoding: UInt? = nil) -> String? {
if nbytes == 0 {
return ""
}
var length = 0
var p = pointer
while true {
let ch = p.assumingMemoryBound(to: UInt8.self).pointee
if ch == 0 {
break
}
p = p.advanced(by: 1)
length += 1
}
let r = readStringN(length, encoding: encoding)
pointer = pointer.advanced(by: nbytes - length)
return r
}
func skip(_ nbytes: Int) {
pointer = pointer.advanced(by: nbytes)
}
}
| 4046d0b99b07af7ff94991e6b4b11de1 | 23.77027 | 115 | 0.520458 | false | false | false | false |
belatrix/BelatrixEventsIOS | refs/heads/master | Hackatrix/Controller/SettingsVC.swift | apache-2.0 | 1 | //
// SettingsVC.swift
// Hackatrix
//
// Created by Erik Fernando Flores Quispe on 9/05/17.
// Copyright © 2017 Belatrix. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class SettingsVC: UIViewController {
//MARK: - Properties
@IBOutlet weak var tableViewSettings: UITableView!
var cities:[City] = []
//MARK: - LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
self.customStyleTableView()
}
//MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == K.segue.citySetting {
let locations = segue.destination as! LocationVC
locations.cities = self.cities
}
}
//MARK: - Functions
func customStyleTableView() {
self.tableViewSettings.tableFooterView = UIView()
}
func getCities(completitionHandler: @escaping () -> Void) {
Alamofire.request(api.url.event.city).responseJSON { response in
if let responseServer = response.result.value {
let json = JSON(responseServer)
for (_,subJson):(String, JSON) in json {
self.cities.append(City(data: subJson))
}
completitionHandler()
}
}
}
}
//MARK: - UITableViewDataSource
extension SettingsVC:UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Localización"
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: K.cell.setting) as! SettingsCell
return cell
}
}
//MARK: - UITableViewDelegate
extension SettingsVC:UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.cities = []
self.getCities {
self.performSegue(withIdentifier: K.segue.citySetting, sender: nil)
}
}
}
| 8e88c6fb68c9cadf1b5251702d6b2610 | 24.9 | 100 | 0.62248 | false | false | false | false |
NathanE73/Blackboard | refs/heads/main | Sources/BlackboardFramework/Availability/Version.swift | mit | 1 | //
// Copyright (c) 2022 Nathan E. Walczak
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
struct Version {
var major: Int
var minor: Int?
var patch: Int?
}
extension Version {
init(_ major: Int, _ minor: Int? = nil, _ patch: Int? = nil) {
self.init(major: major, minor: minor, patch: patch)
}
init?(_ text: String) {
let elements = text.split(separator: ".",
omittingEmptySubsequences: false)
guard elements.count <= 3,
let first = elements.first,
let major = Int(first) else {
return nil
}
guard let second = elements.second else {
self.init(major)
return
}
guard let minor = Int(second) else { return nil }
guard let third = elements.third else {
self.init(major, minor)
return
}
guard let patch = Int(third) else { return nil }
self.init(major, minor, patch)
}
}
extension Version: Comparable {
static func < (lhs: Self, rhs: Self) -> Bool {
let lhs = [lhs.major, lhs.minor ?? 0, lhs.patch ?? 0]
let rhs = [rhs.major, rhs.minor ?? 0, rhs.patch ?? 0]
return lhs.lexicographicallyPrecedes(rhs)
}
}
extension Version: CustomStringConvertible {
var description: String {
[major, minor, patch]
.compactMap { $0?.description }
.joined(separator: ".")
}
}
extension Version: Decodable {
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let text = try container.decode(String.self)
guard let version = Version(text) else {
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Cannot initialize Version")
}
self = version
}
}
| 1206b3cb23b55b6602eb83dc056dff89 | 31.666667 | 80 | 0.617512 | false | false | false | false |
hironytic/FormulaCalc | refs/heads/master | FormulaCalc/View/UIViewController+Transition.swift | mit | 1 | //
// UIViewController+Transition.swift
// FormulaCalc
//
// Copyright (c) 2016, 2017 Hironori Ichimiya <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import RxSwift
public extension UIViewController {
public func transitioner(_ observable: Observable<Message>) -> Disposable {
return observable
.subscribe(onNext: { [unowned self] message in
switch message {
case let message as TransitionMessage:
let viewController = createViewController(for: message.viewModel)
switch message.type {
case .present:
viewController.modalTransitionStyle = message.modalTransitionStyle
self.present(viewController, animated: message.animated, completion: nil)
case .push:
var vc = viewController
if let navvc = vc as? UINavigationController {
vc = navvc.viewControllers[0]
}
self.navigationController?.pushViewController(vc, animated: message.animated)
}
case let message as DismissingMessage:
switch message.type {
case .dismiss:
self.dismiss(animated: message.animated, completion: nil)
case .pop:
_ = self.navigationController?.popViewController(animated: message.animated)
}
default:
break
}
})
}
}
| 141bdac82fea2eeeb376dd1b700c3951 | 43.786885 | 101 | 0.614934 | false | false | false | false |
mkihmouda/ChatRoom | refs/heads/master | ChatRoom/ChatMessagesVC.swift | mit | 1 | //
// ViewController.swift
// IChat
//
// Created by Mac on 12/23/16.
// Copyright © 2016 Mac. All rights reserved.
//
import UIKit
import SocketIO
class ChatMessagesVC: UIViewController,roomMessagesAPIDelegate , getMessageAPIDelegate, SocketData {
// IBOutlet variables
@IBOutlet var scrollView: UIScrollView! // scrollView
@IBOutlet var mainView: MainView! // mainView
@IBOutlet var actiivityIndicator: UIActivityIndicatorView!
// variables
var chatRoomId : String? // room_id
var messageText : String? // message Text
var socket : SocketIOClient! // Socket IO
var roomMessageArray : [ChatMessage]? // messages array
var roomMessagesAPI : RoomMessagesAPI? // Get Messages API
var createMessageAPI : CreateMessageAPI? //Post Messages API
var listScrollModel : ListScrollModel! // scrollView model to handle all scrolling functionalities
// MARK: override UIViewController methods
override func viewDidLoad() {
super.viewDidLoad()
getPreviousMessagesAPI() // call get previous messages API
listScrollModel = ListScrollModel.init(scrollView: self.scrollView) // list scroll model handle all scrolling functionalities
socketConnection() // connect to socket
}
override func viewWillAppear(_ animated: Bool) {
// load subviews
loadSubViews()
}
// MARK: load subViews
func loadSubViews(){
mainView.loadViews(parent: self)
}
// call get previous messages
func getPreviousMessagesAPI(){
roomMessagesAPI = RoomMessagesAPI()
roomMessagesAPI?.delegate = self
self.scrollView.isHidden = true // hide scoll view until finish loading all messages
showActivityIndicator()
roomMessagesAPI?.callAPI {
self.loadMessages() // load messages
}
}
// MARK: socket connection
func socketConnection(){
socket = SocketIOClient.init(socketURL: URL.init(string: SOCKET_URL)!) // init socket
socket.connect() // socket connect
handleSocket() // handle listen operations
}
// handle socket listen operations
func handleSocket(){
self.socket.onAny {
print("Got event: \($0.event), with items: \($0.items)") // for logging operations
}
// listen for socket at channel - chatRoomId
self.socket.on("\(chatRoomId!)", callback: {data, ack in
if let dictionary = data[0] as? Dictionary <String,AnyObject> {
// get message and user_image
if let message = dictionary["message"] as? String, let user_image = dictionary["user_image"] as? String {
// post message
self.mainView.chatView?.postMessage(text: message, automatic: false, senderURL: user_image)
}
}
})
}
// MARK :roomMessagesAPIDelegate methods
func setChatMessagesArray(chatMessagesArray: [ChatMessage]) {
self.roomMessageArray = chatMessagesArray
}
func getRoomId() -> String {
return self.chatRoomId!
}
// load previous message after finish API call
func loadMessages(){
for object in self.roomMessageArray!{
self.mainView.chatView?.addMessagesAutomatically(text: object.text!, image: object.user_image!) // add message
}
// scrolling methods
self.listScrollModel.automaticUpdateScrollWithHiddenKeyboard()
self.listScrollModel.scrollView.contentOffset = CGPoint(x: 0, y: self.listScrollModel.scrollView.contentSize.height - self.listScrollModel.scrollView.bounds.size.height)
self.listScrollModel.automaticUpdateScrollWithHiddenKeyboard()
Timer.scheduledTimer(withTimeInterval: TimeInterval(1.0), repeats: false) { timer in
self.hideActivityIndicator() // hide activity indicator
self.scrollView.isHidden = false // show scroll view
}
}
// MARK :call post message API
func postAPI(text: String){
messageText = text
createMessageAPI = CreateMessageAPI()
createMessageAPI?.delegate = self
createMessageAPI?.callAPI {
self.emitSocket(text: text) // socket emit message
}
}
// emit socket message
func emitSocket(text : String){
let messageData =
["message": text, // text
"room_id": "\(chatRoomId!)", // channel - room id
"user_image" : UserDefaults.standard.value(forKey: "user_image") as! String] // user image
self.socket.emit("Message", messageData) // socket emit message
}
// MARK :getMessageAPIDelegate methods
func getMessageText() -> String {
return messageText!
}
func getMessageRoomId() -> String {
return chatRoomId!
}
// MARK: activityIndicator methods
func showActivityIndicator(){
actiivityIndicator.isHidden = false
actiivityIndicator.startAnimating()
}
func hideActivityIndicator(){
actiivityIndicator.stopAnimating()
actiivityIndicator.isHidden = true
}
// MARK: Button Actions
@IBAction func leaveGroup(_ sender: Any) {
socket.disconnect() // disconnect socket
self.navigationController?.popViewController(animated: true) // return back
}
}
| c228ccb7c6a3891d6f8b4eb6cd962eb3 | 22.782101 | 177 | 0.569535 | false | false | false | false |
julienbodet/wikipedia-ios | refs/heads/develop | Wikipedia/Code/NewsCollectionViewCell+WMFFeedContentDisplaying.swift | mit | 1 | import UIKit
extension NewsCollectionViewCell {
public func configure(with story: WMFFeedNewsStory, dataStore: MWKDataStore, showArticles: Bool = true, theme: Theme, layoutOnly: Bool) {
let previews = story.articlePreviews ?? []
descriptionHTML = story.storyHTML
if showArticles {
articles = previews.map { (articlePreview) -> CellArticle in
return CellArticle(articleURL:articlePreview.articleURL, title: articlePreview.displayTitle, titleHTML: articlePreview.displayTitleHTML, description: articlePreview.descriptionOrSnippet, imageURL: articlePreview.thumbnailURL)
}
}
let articleLanguage = story.articlePreviews?.first?.articleURL.wmf_language
descriptionLabel.accessibilityLanguage = articleLanguage
semanticContentAttributeOverride = MWLanguageInfo.semanticContentAttribute(forWMFLanguage: articleLanguage)
let imageWidthToRequest = traitCollection.wmf_potdImageWidth
if let articleURL = story.featuredArticlePreview?.articleURL ?? previews.first?.articleURL, let article = dataStore.fetchArticle(with: articleURL), let imageURL = article.imageURL(forWidth: imageWidthToRequest) {
isImageViewHidden = false
if !layoutOnly {
imageView.wmf_setImage(with: imageURL, detectFaces: true, onGPU: true, failure: {(error) in }, success: { })
}
} else {
isImageViewHidden = true
}
apply(theme: theme)
setNeedsLayout()
}
}
| e541772dc5863196e5074c4d33df4d32 | 49.548387 | 241 | 0.687939 | false | false | false | false |
huangboju/Moots | refs/heads/master | Examples/UIScrollViewDemo/UIScrollViewDemo/Account/Views/Cells/TextFiledCell.swift | mit | 1 | //
// TextFiledCell.swift
// UIScrollViewDemo
//
// Created by 黄伯驹 on 2017/11/3.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import UIKit
class TextFiledCell: UITableViewCell, Updatable {
typealias FileItem = (placeholder: String?, iconName: String)
final var inputText: String? {
return textField.text
}
final func setField(with item: FileItem) {
var attri: NSAttributedString?
if let placeholder = item.placeholder {
attri = NSAttributedString(string: placeholder, attributes: [
.font: UIFontMake(15)
])
}
textField.attributedPlaceholder = attri
imageView?.image = UIImage(named: item.iconName)
}
final func setRightView(with rightView: UIView?) {
guard let rightView = rightView else {
textField.rightView = nil
textField.rightViewMode = .never
return
}
textField.rightView = rightView
textField.rightViewMode = .always
}
let textField = UITextField()
private let bottomLine = UIView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
contentView.addSubview(textField)
textField.snp.makeConstraints { (make) in
make.leading.equalTo(45)
make.trailing.equalTo(-16)
make.top.bottom.equalTo(self)
}
textField.addTarget(self, action: #selector(editingDidBeginAction), for: .editingDidBegin)
textField.addTarget(self, action: #selector(editingDidEndAction), for: .editingDidEnd)
contentView.addSubview(bottomLine)
bottomLine.snp.makeConstraints { (make) in
make.height.equalTo(1)
make.leading.equalTo(16)
make.trailing.equalTo(-16)
make.bottom.equalToSuperview()
}
bottomLine.backgroundColor = UIColor(hex: 0xCCCCCC)
didInitialzed()
}
open func didInitialzed() {}
@objc
private func editingDidBeginAction() {
bottomLine.backgroundColor = UIColor(hex: 0xA356AB)
}
@objc
private func editingDidEndAction() {
bottomLine.backgroundColor = UIColor(hex: 0xCCCCCC)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func update(viewData: NoneItem) {}
}
| 811d83b0b19dbdc2ec9ec20471cf9a08 | 27.340909 | 98 | 0.630714 | false | false | false | false |
kinetic-fit/sensors-swift | refs/heads/master | Sources/SwiftySensors/CyclingPowerSerializer.swift | mit | 1 | //
// CyclingPowerSerializer.swift
// SwiftySensors
//
// https://github.com/kinetic-fit/sensors-swift
//
// Copyright © 2017 Kinetic. All rights reserved.
//
import Foundation
/// :nodoc:
open class CyclingPowerSerializer {
public struct Features: OptionSet {
public let rawValue: UInt32
public static let PedalPowerBalanceSupported = Features(rawValue: 1 << 0)
public static let AccumulatedTorqueSupported = Features(rawValue: 1 << 1)
public static let WheelRevolutionDataSupported = Features(rawValue: 1 << 2)
public static let CrankRevolutionDataSupported = Features(rawValue: 1 << 3)
public static let ExtremeMagnitudesSupported = Features(rawValue: 1 << 4)
public static let ExtremeAnglesSupported = Features(rawValue: 1 << 5)
public static let TopAndBottomDeadSpotAnglesSupported = Features(rawValue: 1 << 6)
public static let AccumulatedEnergySupported = Features(rawValue: 1 << 7)
public static let OffsetCompensationIndicatorSupported = Features(rawValue: 1 << 8)
public static let OffsetCompensationSupported = Features(rawValue: 1 << 9)
public static let ContentMaskingSupported = Features(rawValue: 1 << 10)
public static let MultipleSensorLocationsSupported = Features(rawValue: 1 << 11)
public static let CrankLengthAdjustmentSupported = Features(rawValue: 1 << 12)
public static let ChainLengthAdjustmentSupported = Features(rawValue: 1 << 13)
public static let ChainWeightAdjustmentSupported = Features(rawValue: 1 << 14)
public static let SpanLengthAdjustmentSupported = Features(rawValue: 1 << 15)
public static let SensorMeasurementContext = Features(rawValue: 1 << 16)
public static let InstantaneousMeasurementDirectionSupported = Features(rawValue: 1 << 17)
public static let FactoryCalibrationDateSupported = Features(rawValue: 1 << 18)
public init(rawValue: UInt32) {
self.rawValue = rawValue
}
}
public static func readFeatures(_ data: Data) -> Features {
let bytes = data.map { $0 }
var rawFeatures: UInt32 = 0
if bytes.count > 0 { rawFeatures |= UInt32(bytes[0]) }
if bytes.count > 1 { rawFeatures |= UInt32(bytes[1]) << 8 }
if bytes.count > 2 { rawFeatures |= UInt32(bytes[2]) << 16 }
if bytes.count > 3 { rawFeatures |= UInt32(bytes[3]) << 24 }
return Features(rawValue: rawFeatures)
}
struct MeasurementFlags: OptionSet {
let rawValue: UInt16
static let PedalPowerBalancePresent = MeasurementFlags(rawValue: 1 << 0)
static let AccumulatedTorquePresent = MeasurementFlags(rawValue: 1 << 2)
static let WheelRevolutionDataPresent = MeasurementFlags(rawValue: 1 << 4)
static let CrankRevolutionDataPresent = MeasurementFlags(rawValue: 1 << 5)
static let ExtremeForceMagnitudesPresent = MeasurementFlags(rawValue: 1 << 6)
static let ExtremeTorqueMagnitudesPresent = MeasurementFlags(rawValue: 1 << 7)
static let ExtremeAnglesPresent = MeasurementFlags(rawValue: 1 << 8)
static let TopDeadSpotAnglePresent = MeasurementFlags(rawValue: 1 << 9)
static let BottomDeadSpotAnglePresent = MeasurementFlags(rawValue: 1 << 10)
static let AccumulatedEnergyPresent = MeasurementFlags(rawValue: 1 << 11)
static let OffsetCompensationIndicator = MeasurementFlags(rawValue: 1 << 12)
}
public struct MeasurementData: CyclingMeasurementData {
public var timestamp: Double = 0
public var instantaneousPower: Int16 = 0
public var pedalPowerBalance: UInt8?
public var pedalPowerBalanceReference: Bool?
public var accumulatedTorque: UInt16?
public var cumulativeWheelRevolutions: UInt32?
public var lastWheelEventTime: UInt16?
public var cumulativeCrankRevolutions: UInt16?
public var lastCrankEventTime: UInt16?
public var maximumForceMagnitude: Int16?
public var minimumForceMagnitude: Int16?
public var maximumTorqueMagnitude: Int16?
public var minimumTorqueMagnitude: Int16?
public var maximumAngle: UInt16?
public var minimumAngle: UInt16?
public var topDeadSpotAngle: UInt16?
public var bottomDeadSpotAngle: UInt16?
public var accumulatedEnergy: UInt16?
}
public static func readMeasurement(_ data: Data) -> MeasurementData {
var measurement = MeasurementData()
let bytes = data.map { $0 }
var index: Int = 0
if bytes.count >= 2 {
let rawFlags: UInt16 = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
let flags = MeasurementFlags(rawValue: rawFlags)
if bytes.count >= 4 {
measurement.instantaneousPower = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8
if flags.contains(.PedalPowerBalancePresent) && bytes.count >= index {
measurement.pedalPowerBalance = bytes[index++=]
measurement.pedalPowerBalanceReference = rawFlags & 0x2 == 0x2
}
if flags.contains(.AccumulatedTorquePresent) && bytes.count >= index + 1 {
measurement.accumulatedTorque = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
if flags.contains(.WheelRevolutionDataPresent) && bytes.count >= index + 6 {
var cumulativeWheelRevolutions = UInt32(bytes[index++=])
cumulativeWheelRevolutions |= UInt32(bytes[index++=]) << 8
cumulativeWheelRevolutions |= UInt32(bytes[index++=]) << 16
cumulativeWheelRevolutions |= UInt32(bytes[index++=]) << 24
measurement.cumulativeWheelRevolutions = cumulativeWheelRevolutions
measurement.lastWheelEventTime = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
if flags.contains(.CrankRevolutionDataPresent) && bytes.count >= index + 4 {
measurement.cumulativeCrankRevolutions = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
measurement.lastCrankEventTime = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
if flags.contains(.ExtremeForceMagnitudesPresent) && bytes.count >= index + 4 {
measurement.maximumForceMagnitude = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8
measurement.minimumForceMagnitude = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8
}
if flags.contains(.ExtremeTorqueMagnitudesPresent) && bytes.count >= index + 4 {
measurement.maximumTorqueMagnitude = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8
measurement.minimumTorqueMagnitude = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8
}
if flags.contains(.ExtremeAnglesPresent) && bytes.count >= index + 3 {
// TODO: this bit shifting is not correct.
measurement.minimumAngle = UInt16(bytes[index++=]) | UInt16(bytes[index] & 0xF0) << 4
measurement.maximumAngle = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 4
}
if flags.contains(.TopDeadSpotAnglePresent) && bytes.count >= index + 2 {
measurement.topDeadSpotAngle = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
if flags.contains(.BottomDeadSpotAnglePresent) && bytes.count >= index + 2 {
measurement.bottomDeadSpotAngle = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
if flags.contains(.AccumulatedEnergyPresent) && bytes.count >= index + 2 {
measurement.accumulatedEnergy = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
}
}
measurement.timestamp = Date.timeIntervalSinceReferenceDate
return measurement
}
struct VectorFlags: OptionSet {
let rawValue: UInt8
static let CrankRevolutionDataPresent = VectorFlags(rawValue: 1 << 0)
static let FirstCrankAnglePresent = VectorFlags(rawValue: 1 << 1)
static let InstantaneousForcesPresent = VectorFlags(rawValue: 1 << 2)
static let InstantaneousTorquesPresent = VectorFlags(rawValue: 1 << 3)
}
public struct VectorData {
public enum MeasurementDirection {
case unknown
case tangentialComponent
case radialComponent
case lateralComponent
}
public var instantaneousMeasurementDirection: MeasurementDirection = .unknown
public var cumulativeCrankRevolutions: UInt16?
public var lastCrankEventTime: UInt16?
public var firstCrankAngle: UInt16?
public var instantaneousForce: [Int16]?
public var instantaneousTorque: [Double]?
}
public static func readVector(_ data: Data) -> VectorData {
var vector = VectorData()
let bytes = data.map { $0 }
let flags = VectorFlags(rawValue: bytes[0])
let measurementDirection = (bytes[0] & 0x30) >> 4
switch measurementDirection {
case 0:
vector.instantaneousMeasurementDirection = .unknown
case 1:
vector.instantaneousMeasurementDirection = .tangentialComponent
case 2:
vector.instantaneousMeasurementDirection = .radialComponent
case 3:
vector.instantaneousMeasurementDirection = .lateralComponent
default:
vector.instantaneousMeasurementDirection = .unknown
}
var index: Int = 1
if flags.contains(.CrankRevolutionDataPresent) {
vector.cumulativeCrankRevolutions = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
vector.lastCrankEventTime = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
if flags.contains(.FirstCrankAnglePresent) {
vector.firstCrankAngle = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
// These two arrays are mutually exclusive
if flags.contains(.InstantaneousForcesPresent) {
} else if flags.contains(.InstantaneousTorquesPresent) {
let torqueRaw = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8
let torque = Double(torqueRaw) / 32.0
print(torque)
}
return vector
}
}
| 3a93547e272ea67c7b68e981f4d24483 | 47.798283 | 115 | 0.591733 | false | false | false | false |
flibbertigibbet/CycleSaver | refs/heads/develop | CycleSaver/Controllers/TripListController.swift | apache-2.0 | 1 | //
// TripListController.swift
// CycleSaver
//
// Created by Kathryn Killebrew on 12/5/15.
// Copyright © 2015 Kathryn Killebrew. All rights reserved.
//
import Foundation
import UIKit
import CoreData
private let tripCellIdentifier = "tripCellReuseIdentifier"
class TripListController: UIViewController {
@IBOutlet weak var tripTableView: UITableView!
var fetchedResultsController : NSFetchedResultsController!
lazy var coreDataStack = (UIApplication.sharedApplication().delegate as! AppDelegate).coreDataStack
let formatter = NSDateFormatter()
override func viewDidLoad() {
super.viewDidLoad()
formatter.dateStyle = .ShortStyle
formatter.timeStyle = .ShortStyle
let fetchRequest = NSFetchRequest(entityName: "Trip")
let startSort = NSSortDescriptor(key: "start", ascending: true)
let stopSort = NSSortDescriptor(key: "stop", ascending: true)
fetchRequest.sortDescriptors = [startSort, stopSort]
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: coreDataStack.context, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController.delegate = self
tripTableView.delegate = self
do {
try fetchedResultsController.performFetch()
tripTableView.reloadData()
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
}
func configureCell(cell: TripCell, indexPath: NSIndexPath) {
let trip = fetchedResultsController.objectAtIndexPath(indexPath) as! Trip
if let tripStart = trip.start {
cell.startLabel.text = formatter.stringFromDate(tripStart)
}
if let tripStop = trip.stop {
cell.stopLabel.text = formatter.stringFromDate(tripStop)
}
cell.coordsCount.text = "???"
// TODO: how to get related obj
}
}
extension TripListController: UITableViewDataSource {
func numberOfSectionsInTableView (tableView: UITableView) -> Int {
return fetchedResultsController.sections!.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let sectionInfo = fetchedResultsController.sections![section]
return sectionInfo.name
}
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
let sectionInfo =
fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(tripCellIdentifier, forIndexPath: indexPath) as! TripCell
configureCell(cell, indexPath: indexPath)
return cell
}
}
extension TripListController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let trip = fetchedResultsController.objectAtIndexPath(indexPath) as! Trip
print("Selected trip that started at \(trip.start).")
self.performSegueWithIdentifier("ShowTripMap", sender: trip)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "ShowTripMap") {
if let tripMapController = segue.destinationViewController as? TripDetailController {
tripMapController.trip = sender as? Trip
tripMapController.coreDataStack = coreDataStack
}
}
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
switch editingStyle {
case .Delete:
// delete from data source here; this will then trigger deletion on the NSFetchedResultsControllerDelegate, which updates the view
let trip = fetchedResultsController.objectAtIndexPath(indexPath) as! Trip
coreDataStack.context.deleteObject(trip)
coreDataStack.saveContext()
default: break
}
}
}
extension TripListController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(controller: NSFetchedResultsController) {
tripTableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tripTableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
case .Delete:
tripTableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
case .Update:
let cell = tripTableView.cellForRowAtIndexPath(indexPath!) as! TripCell
configureCell(cell, indexPath: indexPath!)
case .Move:
tripTableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
tripTableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tripTableView.endUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int,forChangeType type: NSFetchedResultsChangeType) {
let indexSet = NSIndexSet(index: sectionIndex)
switch type {
case .Insert:
tripTableView.insertSections(indexSet, withRowAnimation: .Automatic)
case .Delete:
tripTableView.deleteSections(indexSet, withRowAnimation: .Automatic)
default :
break
}
}
}
| 20518aa2d227ee7d6c16a24eef701b65 | 35.757396 | 211 | 0.682711 | false | false | false | false |
fredfoc/OpenWit | refs/heads/master | Example/OpenWit/Examples/Manager/OpenWitConversationManager.swift | mit | 1 | //
// OpenWitConversationManager.swift
// OpenWit
//
// Created by fauquette fred on 7/01/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import OpenWit
import ObjectMapper
/// Your logic to analyse Wit answers could go there
class OpenWitConversationManager {
typealias ConversationCompletion = ((String) -> ())?
private var converseSessionId = "1234"
private var nextConverseType = OpenWitConverseType.unknwon
func startConversation(_ message: String? = nil, context: Mappable? = nil, completion: ConversationCompletion = nil) {
converseSessionId = String.randomString(length: 10)
if let message = message {
converse(message, context: context, completion: completion)
}
}
/// this will analyse the conversation (returns of Wit Api)
///
/// - Parameter context: an optional context
func converse(_ message: String, context: Mappable? = nil, completion: ConversationCompletion = nil) {
OpenWit
.sharedInstance
.conversationMessage(message,
sessionId: converseSessionId,
context: context) {[unowned self] result in
switch result {
case .success(let converse):
/// Your logic should start here... :-)
var message: String?
self.nextConverseType = converse.type
switch converse.type {
case .action:
if let action = converse.action {
switch action {
case "addShopItem":
self.addShopItem(converse: converse, context: context, completion: completion)
case "createList":
self.createList(converse: converse, context: context, completion: completion)
default:
break
}
}
case .msg:
message = converse.msg!
case .merge:
message = "some merge"
case .stop:
message = "Merci (Fin de la conversation)"
case .unknwon:
message = "Oupss..."
}
if let message = message {
completion?(message)
}
case .failure(let error):
print(error)
}
}
}
/// In case we get a createList action from Wit
///
/// - Parameters:
/// - converse: the return from Wit
/// - context: an optional context
private func createList(converse: OpenWitConverseModel, context: Mappable? = nil, completion: ConversationCompletion){
let createListAnswerModel: CreateListAnswerModel
if let shopList = converse.shopList {
createListAnswerModel = CreateListAnswerModel(listName: shopList.value, missingListName: nil)
} else {
createListAnswerModel = CreateListAnswerModel(listName: nil, missingListName: "something is missing here")
}
OpenWit.sharedInstance.conversationAction(createListAnswerModel,
sessionId: converseSessionId,
context: context) {[unowned self] result in
switch result {
case .success(let converse):
/// Your logic should start here... :-)
var message: String?
self.nextConverseType = converse.type
switch converse.type {
case .action:
print(converse)
case .msg:
message = converse.msg!
case .merge:
message = "some merge"
case .stop:
message = "Merci (Fin de la conversation)"
case .unknwon:
message = "Oupss..."
}
if let message = message {
completion?(message)
}
case .failure(let error):
print(error)
}
}
}
/// In case we get a addShopItem form Wit action from Wit
///
/// - Parameters:
/// - converse: the return from Wit
/// - context: an optional context
private func addShopItem(converse: OpenWitConverseModel, context: Mappable? = nil, completion: ConversationCompletion){
let addShopItemAnswerModel: AddShopItemAnswerModel
if let shopItem = converse.shopItem, let shopList = converse.shopList {
addShopItemAnswerModel = AddShopItemAnswerModel(allOk: (shopItem.value ?? "strange product") + " ajouté à " + (shopList.value ?? "strange list"),
shopListAlone: nil,
shopItemAlone: nil,
missingAll: nil)
} else if let shopItem = converse.shopItem {
addShopItemAnswerModel = AddShopItemAnswerModel(allOk: nil,
shopListAlone: nil,
shopItemAlone: shopItem.value,
missingAll: nil)
} else if let shopList = converse.shopList {
addShopItemAnswerModel = AddShopItemAnswerModel(allOk: nil,
shopListAlone: shopList.value,
shopItemAlone: nil,
missingAll: nil)
} else {
addShopItemAnswerModel = AddShopItemAnswerModel(allOk: nil,
shopListAlone: nil,
shopItemAlone: nil,
missingAll: true)
}
OpenWit.sharedInstance.conversationAction(addShopItemAnswerModel,
sessionId: converseSessionId,
context: context) {[unowned self] result in
switch result {
case .success(let converse):
/// Your logic should start here... :-)
var message: String?
self.nextConverseType = converse.type
switch converse.type {
case .action:
self.addShopItem(converse: converse, context: context, completion: completion)
case .msg:
message = converse.msg!
case .merge:
message = "some merge"
case .stop:
message = "Merci (Fin de la conversation)"
case .unknwon:
message = "Oupss..."
}
if let message = message {
completion?(message)
}
case .failure(let error):
print(error)
}
}
}
}
| e0c9d7ddac4d980ef75742598489a9c5 | 56.662857 | 158 | 0.351105 | false | false | false | false |
Alienson/Bc | refs/heads/master | source-code/GameScene-zalohaOld.swift | apache-2.0 | 1 | //
// GameScene.swift
// Parketovanie
//
// Created by Adam Turna on 4.1.2016.
// Copyright (c) 2016 Adam Turna. All rights reserved.
//
import SpriteKit
import Foundation
private let movableString = "movable"
class GameScene: SKScene {
var listOfParquets: [Parquet] = []
var selectedNode = SKSpriteNode()
let background = SKSpriteNode(imageNamed: "hracia_plocha_lvl1")
var surfaceBackground = SKSpriteNode()
var surf = Surface()
let panRec = UIPanGestureRecognizer()
override init(size: CGSize) {
super.init(size: size)
anchorPoint = CGPoint(x: 0.0, y: 0.0)
self.background.name = "background"
self.background.position = CGPoint(x: 0, y: 0)
self.background.anchorPoint = CGPoint(x: 0, y: 0)
addChild(self.background)
leftBarlvl1()
makeSurface()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToView(view: SKView) {
let gestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("handlePanFrom:"))
self.view!.addGestureRecognizer(gestureRecognizer)
let doubleTap = UITapGestureRecognizer(target: self, action: "doubleTapped")
doubleTap.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTap)
// panRec.addTarget(self, action: "panned:")
// panRec.maximumNumberOfTouches = 1
// self.view!.addGestureRecognizer(panRec)
}
func panned(sender: UIPanGestureRecognizer){
var touchLocation: CGPoint = sender.locationInView(self.view!)
touchLocation = self.convertPointFromView(touchLocation)
}
func doubleTapped() {
if selectedNode.name == "parquet" {
print(selectedNode.name)
//selectedNode.anchorPoint = CGPoint(x: 0.5, y: 0.5)
selectedNode.runAction(SKAction.rotateByAngle(degToRad(90.0), duration: 0.1))
//selectedNode.anchorPoint = CGPoint(x: 0, y: 0)
}
}
func handlePanFrom(recognizer : UIPanGestureRecognizer) {
if recognizer.state == .Began {
var touchLocation = recognizer.locationInView(recognizer.view)
touchLocation = self.convertPointFromView(touchLocation)
self.selectNodeForTouch(touchLocation)
print("began \(touchLocation)")
} else if recognizer.state == .Changed {
var translation = recognizer.translationInView(recognizer.view!)
translation = CGPoint(x: translation.x, y: -translation.y)
self.panForTranslation(translation)
recognizer.setTranslation(CGPointZero, inView: recognizer.view)
print("changed")
} else if recognizer.state == .Ended {
print("ended")
if selectedNode.name != "parquet" {
print("tu")
// let scrollDuration = 0.2
// let velocity = recognizer.velocityInView(recognizer.view)
// let pos = selectedNode.position
//
// // This just multiplies your velocity with the scroll duration.
// let p = CGPoint(x: velocity.x * CGFloat(scrollDuration), y: velocity.y * CGFloat(scrollDuration))
//
// var newPos = CGPoint(x: pos.x + p.x, y: pos.y + p.y)
// newPos = self.boundLayerPos(newPos)
// selectedNode.removeAllActions()
//
// let moveTo = SKAction.moveTo(newPos, duration: scrollDuration)
// moveTo.timingMode = .EaseOut
// selectedNode.runAction(moveTo)
}
}
}
func degToRad(degree: Double) -> CGFloat {
return CGFloat(degree / 180.0 * M_PI)
}
func selectNodeForTouch(touchLocation : CGPoint) {
// 1
let touchedNode = self.nodeAtPoint(touchLocation)
if touchedNode.name == "parquet" {
// 2
if !selectedNode.isEqual(touchedNode) {
selectedNode.removeAllActions()
selectedNode = touchedNode as! SKSpriteNode
}
else {
selectedNode = SKSpriteNode()
}
}
}
func deSelectNodeForTouch(touchLocation : CGPoint) {
selectedNode = SKSpriteNode()
}
func panForTranslation(translation : CGPoint) {
let position = selectedNode.position
if selectedNode.isMemberOfClass(Parquet){
print(selectedNode.name)
selectedNode.position = CGPoint(x: position.x + translation.x, y: position.y + translation.y)
}
}
func boundLayerPos(aNewPosition : CGPoint) -> CGPoint {
let winSize = self.size
var retval = aNewPosition
retval.x = CGFloat(min(retval.x, 0))
retval.x = CGFloat(max(retval.x, -(background.size.width) + winSize.width))
retval.y = self.position.y
return retval
}
func makeSurface() {
surfaceBackground = SKSpriteNode(texture: nil, color: UIColor.purpleColor(), size: CGSize(width: 743, height: 550))
surfaceBackground.anchorPoint = CGPoint(x: 0.0, y: 0.0)
surfaceBackground.name = "surfaceBackground"
surfaceBackground.position = CGPoint(x: 280, y: 176)
surfaceBackground.alpha = CGFloat(0.5)
addChild(surfaceBackground)
self.surf = Surface(rows: 3, collumns: 4, parent: surfaceBackground)
}
func leftBarlvl1() {
// let leftBar = SKSpriteNode(imageNamed: "lava_lista")
// leftBar.position = CGPoint(x:0, y: 0)
// leftBar.anchorPoint = CGPoint(x: 0, y: 0)
// leftBar.name = "lava_lista"
// background.addChild(leftBar)
//
let offset = CGFloat(12.5)
let offsetY = CGFloat(100)
let width = CGFloat(280)
let firstLineParquets = CGFloat(250)
let secondLineParquets = CGFloat(150)
// _ = leftBar.size.height
// let width = leftBar.size.width
let mono = Parquet(imageNamed: "1-mono")
mono.position = CGPointMake(width / 4 - offset, offsetY+firstLineParquets)
mono.anchorPoint = CGPoint(x: 0.5, y: 0.5)
let duo = Parquet(imageNamed: "2-duo")
duo.position = CGPointMake(width / 2, offsetY+firstLineParquets+25)
duo.anchorPoint = CGPoint(x: 0.5, y: 0.5)
let trio = Parquet(imageNamed: "3-3I")
trio.position = CGPointMake(3 * width / 4 + offset, offsetY+firstLineParquets+50)
trio.anchorPoint = CGPoint(x: 0.5, y: 0.5)
let roztek = Parquet(imageNamed: "4-roztek")
roztek.position = CGPointMake(width / 3 - offset, offsetY+secondLineParquets)
roztek.anchorPoint = CGPoint(x: 0.5, y: 0.5)
let stvorka = Parquet(imageNamed: "5-stvorka")
stvorka.position = CGPointMake(2 * width / 3 + offset, offsetY+secondLineParquets)
stvorka.anchorPoint = CGPoint(x: 0.5, y: 0.5)
let elko = Parquet(imageNamed: "6-elko")
elko.position = CGPointMake(width / 3 - offset, offsetY)
elko.anchorPoint = CGPoint(x: 0.5, y: 0.5)
let elko_obratene = Parquet(imageNamed: "7-elko-obratene")
elko_obratene.position = CGPointMake(2 * width / 3 + offset, offsetY)
elko_obratene.anchorPoint = CGPoint(x: 0.5, y: 0.5)
listOfParquets.append(mono)
listOfParquets.append(duo)
listOfParquets.append(trio)
listOfParquets.append(roztek)
listOfParquets.append(stvorka)
listOfParquets.append(elko)
listOfParquets.append(elko_obratene)
for par in listOfParquets {
par.movable = true
par.zPosition = 0
background.addChild(par)
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
let location = touch.locationInNode(self)
let touchedNode = nodeAtPoint(location)
touchedNode.zPosition = 15
//let liftUp = SKAction.scaleTo(1.2, duration: 0.2)
//touchedNode.runAction(liftUp, withKey: "pickup")
selectNodeForTouch(location)
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
let location = touch.locationInNode(self)
let touchedNode = nodeAtPoint(location)
touchedNode.zPosition = 0
//let dropDown = SKAction.scaleTo(1.0, duration: 0.2)
touchedNode.position.x = touchedNode.position.x - touchedNode.position.x % 10
//point.x - point.x % 10
touchedNode.position.y = touchedNode.position.y - touchedNode.position.y % 10
//touchedNode.runAction(dropDown, withKey: "drop")
//print(touchedNode.position)
deSelectNodeForTouch(location)
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self)
deSelectNodeForTouch(location)
//selectedNode = SKSpriteNode()
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
extension UIColor {
public convenience init?(hexString: String) {
let r, g, b, a: CGFloat
if hexString.hasPrefix("#") {
let start = hexString.startIndex.advancedBy(1)
let hexColor = hexString.substringFromIndex(start)
if hexColor.characters.count == 8 {
let scanner = NSScanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexLongLong(&hexNumber) {
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
a = CGFloat(hexNumber & 0x000000ff) / 255
self.init(red: r, green: g, blue: b, alpha: a)
return
}
}
}
return nil
}
} | fe11f294a305b85a4fdecd5884e7963f | 34.754967 | 123 | 0.572566 | false | false | false | false |
xu6148152/binea_project_for_ios | refs/heads/master | ToDoListDemo/ToDoListDemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// ToDoListDemo
//
// Created by Binea Xu on 15/2/24.
// Copyright (c) 2015年 Binea Xu. All rights reserved.
//
import UIKit
var todos: [ToDoBean] = []
var filterTodos: [ToDoBean] = []
func dateFromString(dateStr: String)->NSDate?{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.dateFromString(dateStr)
return date
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
todos = [ToDoBean(id: "1", image: "child-selected", title: "1. 去游乐场", date: dateFromString("2014-10-20")!),
ToDoBean(id: "2", image: "shopping-cart-selected", title: "2. 购物", date: dateFromString("2014-10-28")!),
ToDoBean(id: "3", image: "phone-selected", title: "3. 打电话", date: dateFromString("2014-10-30")!),
ToDoBean(id: "4", image: "travel-selected", title: "4. Travel to Europe", date: dateFromString("2014-10-31")!)]
tableView.dataSource = self
navigationItem.leftBarButtonItem = editButtonItem()
// hide the search bar
var contentOffset = tableView.contentOffset
contentOffset.y += searchDisplayController!.searchBar.frame.size.height
tableView.contentOffset = contentOffset
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if tableView == searchDisplayController?.searchResultsTableView{
return filterTodos.count
}
return todos.count
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = self.tableView.dequeueReusableCellWithIdentifier("todoCell") as UITableViewCell
var todo : ToDoBean
if tableView == searchDisplayController?.searchResultsTableView{
todo = filterTodos[indexPath.row] as ToDoBean
}else{
todo = todos[indexPath.row] as ToDoBean
}
var image = cell.viewWithTag(101) as UIImageView
var title = cell.viewWithTag(102) as UILabel
var date = cell.viewWithTag(103) as UILabel
image.image = UIImage(named: todo.image)
title.text = todo.title
let locale = NSLocale.currentLocale()
let dateFormat = NSDateFormatter.dateFormatFromTemplate("yyyy-MM-dd ", options: 0, locale: locale)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
date.text = dateFormatter.stringFromDate(todo.date)
return cell
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete{
todos.removeAtIndex(indexPath.row)
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
//edit
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.setEditing(editing, animated: true)
}
@IBAction func close(segue: UIStoryboardSegue){
tableView.reloadData()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EditTodo" {
var vc = segue.destinationViewController as DetailViewController
// var indexPath = tableView.indexPathForCell(sender as UITableViewCell)
var indexPath = tableView.indexPathForSelectedRow()
if let index = indexPath {
vc.todo = todos[index.row]
}
}
}
// Move the cell
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return self.editing
}
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
let todo = todos.removeAtIndex(sourceIndexPath.row)
todos.insert(todo, atIndex: destinationIndexPath.row)
}
func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String!) -> Bool {
filterTodos = todos.filter(){$0.title.rangeOfString(searchString) != nil}
return true
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
}
| 431df747678c17b8644e19147e8a3aa7 | 38.266667 | 188 | 0.676476 | false | false | false | false |
davidbutz/ChristmasFamDuels | refs/heads/master | iOS/Boat Aware/selectwifiTableViewController.swift | mit | 1 | //
// selectwifiTableViewController.swift
// ThriveIOSPrototype
//
// Created by Dave Butz on 1/11/16.
// Copyright © 2016 Dave Butz. All rights reserved.
//
import UIKit
class selectwifiTableViewController: UITableViewController {
@IBOutlet weak var tblView: UITableView!
typealias JSONArray = Array<AnyObject>
typealias JSONDictionary = Dictionary<String, AnyObject>
var wifiList : JSONArray = []
let appvar = ApplicationVariables.applicationvariables;
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
// Do any additional setup after loading the view.
// get wifi data...
let JSONObject: [String : AnyObject] = [
"userid" : appvar.userid
]
let api = APICalls();
api.apicallout("/api/setupwifi/scanwifi" , iptype: "thriveIPAddress", method: "POST", JSONObject: JSONObject, callback: { (response) -> () in
//handle the response. i should get status : fail/success and message: various
let status = (response as! NSDictionary)["status"] as! Bool;
if(status){
let networks = (response as! NSDictionary)["networks"] as! Array<Dictionary<String, AnyObject>>;
self.wifiList = networks;
self.tblView.reloadData();
}
});
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1;//wifiList.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return wifiList.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("wificell", forIndexPath: indexPath)
// Configure the cell...
var wifi = wifiList[indexPath.row] as! JSONDictionary
let wifiname = wifi["ssid"] as! String;
let security = wifi["security"] as! String;
cell.textLabel!.text = wifiname;
cell.detailTextLabel!.text = security;
return cell;
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Process an Selection
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| c3599333bf0282ba059d8cf770f49f89 | 35.914063 | 157 | 0.665397 | false | false | false | false |
KrauseFx/fastlane | refs/heads/master | fastlane/swift/SocketClient.swift | mit | 1 | // SocketClient.swift
// Copyright (c) 2022 FastlaneTools
//
// ** NOTE **
// This file is provided by fastlane and WILL be overwritten in future updates
// If you want to add extra functionality to this project, create a new file in a
// new group so that it won't be marked for upgrade
//
import Dispatch
import Foundation
public enum SocketClientResponse: Error {
case alreadyClosedSockets
case malformedRequest
case malformedResponse
case serverError
case clientInitiatedCancelAcknowledged
case commandTimeout(seconds: Int)
case connectionFailure
case success(returnedObject: String?, closureArgumentValue: String?)
}
class SocketClient: NSObject {
enum SocketStatus {
case ready
case closed
}
static let connectTimeoutSeconds = 2
static let defaultCommandTimeoutSeconds = 10800 // 3 hours
static let doneToken = "done" // TODO: remove these
static let cancelToken = "cancelFastlaneRun"
fileprivate var inputStream: InputStream!
fileprivate var outputStream: OutputStream!
fileprivate var cleaningUpAfterDone = false
fileprivate let dispatchGroup = DispatchGroup()
fileprivate let readSemaphore = DispatchSemaphore(value: 1)
fileprivate let writeSemaphore = DispatchSemaphore(value: 1)
fileprivate let commandTimeoutSeconds: Int
private let writeQueue: DispatchQueue
private let readQueue: DispatchQueue
private let streamQueue: DispatchQueue
private let host: String
private let port: UInt32
let maxReadLength = 65536 // max for ipc on 10.12 is kern.ipc.maxsockbuf: 8388608 ($sysctl kern.ipc.maxsockbuf)
private(set) weak var socketDelegate: SocketClientDelegateProtocol?
public private(set) var socketStatus: SocketStatus
// localhost only, this prevents other computers from connecting
init(host: String = "localhost", port: UInt32 = 2000, commandTimeoutSeconds: Int = defaultCommandTimeoutSeconds, socketDelegate: SocketClientDelegateProtocol) {
self.host = host
self.port = port
self.commandTimeoutSeconds = commandTimeoutSeconds
readQueue = DispatchQueue(label: "readQueue", qos: .background, attributes: .concurrent)
writeQueue = DispatchQueue(label: "writeQueue", qos: .background, attributes: .concurrent)
streamQueue = DispatchQueue.global(qos: .background)
socketStatus = .closed
self.socketDelegate = socketDelegate
super.init()
}
func connectAndOpenStreams() {
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
streamQueue.sync {
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, self.host as CFString, self.port, &readStream, &writeStream)
self.inputStream = readStream!.takeRetainedValue()
self.outputStream = writeStream!.takeRetainedValue()
self.inputStream.delegate = self
self.outputStream.delegate = self
self.inputStream.schedule(in: .main, forMode: .defaultRunLoopMode)
self.outputStream.schedule(in: .main, forMode: .defaultRunLoopMode)
}
dispatchGroup.enter()
readQueue.sync {
self.inputStream.open()
}
dispatchGroup.enter()
writeQueue.sync {
self.outputStream.open()
}
let secondsToWait = DispatchTimeInterval.seconds(SocketClient.connectTimeoutSeconds)
let connectTimeout = DispatchTime.now() + secondsToWait
let timeoutResult = dispatchGroup.wait(timeout: connectTimeout)
let failureMessage = "Couldn't connect to ruby process within: \(SocketClient.connectTimeoutSeconds) seconds"
let success = testDispatchTimeoutResult(timeoutResult, failureMessage: failureMessage, timeToWait: secondsToWait)
guard success else {
socketDelegate?.commandExecuted(serverResponse: .connectionFailure) { _ in }
return
}
socketStatus = .ready
socketDelegate?.connectionsOpened()
}
public func send(rubyCommand: RubyCommandable) {
verbose(message: "sending: \(rubyCommand.json)")
send(string: rubyCommand.json)
writeSemaphore.signal()
}
public func sendComplete() {
closeSession(sendAbort: true)
}
private func testDispatchTimeoutResult(_ timeoutResult: DispatchTimeoutResult, failureMessage: String, timeToWait: DispatchTimeInterval) -> Bool {
switch timeoutResult {
case .success:
return true
case .timedOut:
log(message: "Timeout: \(failureMessage)")
if case let .seconds(seconds) = timeToWait {
socketDelegate?.commandExecuted(serverResponse: .commandTimeout(seconds: seconds)) { _ in }
}
return false
}
}
private func stopInputSession() {
inputStream.close()
}
private func stopOutputSession() {
outputStream.close()
}
private func sendThroughQueue(string: String) {
let data = string.data(using: .utf8)!
data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
if let buffer = buffer.baseAddress {
self.outputStream.write(buffer.assumingMemoryBound(to: UInt8.self), maxLength: data.count)
}
}
}
private func privateSend(string: String) {
writeQueue.sync {
writeSemaphore.wait()
self.sendThroughQueue(string: string)
writeSemaphore.signal()
let timeoutSeconds = self.cleaningUpAfterDone ? 1 : self.commandTimeoutSeconds
let timeToWait = DispatchTimeInterval.seconds(timeoutSeconds)
let commandTimeout = DispatchTime.now() + timeToWait
let timeoutResult = writeSemaphore.wait(timeout: commandTimeout)
_ = self.testDispatchTimeoutResult(timeoutResult, failureMessage: "Ruby process didn't return after: \(SocketClient.connectTimeoutSeconds) seconds", timeToWait: timeToWait)
}
}
private func send(string: String) {
guard !cleaningUpAfterDone else {
// This will happen after we abort if there are commands waiting to be executed
// Need to check state of SocketClient in command runner to make sure we can accept `send`
socketDelegate?.commandExecuted(serverResponse: .alreadyClosedSockets) { _ in }
return
}
if string == SocketClient.doneToken {
cleaningUpAfterDone = true
}
privateSend(string: string)
}
func closeSession(sendAbort: Bool = true) {
socketStatus = .closed
stopInputSession()
if sendAbort {
send(rubyCommand: ControlCommand(commandType: .done))
}
stopOutputSession()
socketDelegate?.connectionsClosed()
}
public func enter() {
dispatchGroup.enter()
}
public func leave() {
readSemaphore.signal()
writeSemaphore.signal()
}
}
extension SocketClient: StreamDelegate {
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
guard !cleaningUpAfterDone else {
// Still getting response from server eventhough we are done.
// No big deal, we're closing the streams anyway.
// That being said, we need to balance out the dispatchGroups
dispatchGroup.leave()
return
}
if aStream === inputStream {
switch eventCode {
case Stream.Event.openCompleted:
dispatchGroup.leave()
case Stream.Event.errorOccurred:
verbose(message: "input stream error occurred")
closeSession(sendAbort: true)
case Stream.Event.hasBytesAvailable:
read()
case Stream.Event.endEncountered:
// nothing special here
break
case Stream.Event.hasSpaceAvailable:
// we don't care about this
break
default:
verbose(message: "input stream caused unrecognized event: \(eventCode)")
}
} else if aStream === outputStream {
switch eventCode {
case Stream.Event.openCompleted:
dispatchGroup.leave()
case Stream.Event.errorOccurred:
// probably safe to close all the things because Ruby already disconnected
verbose(message: "output stream recevied error")
case Stream.Event.endEncountered:
// nothing special here
break
case Stream.Event.hasSpaceAvailable:
// we don't care about this
break
default:
verbose(message: "output stream caused unrecognized event: \(eventCode)")
}
}
}
func read() {
readQueue.sync {
self.readSemaphore.wait()
var buffer = [UInt8](repeating: 0, count: maxReadLength)
var output = ""
while self.inputStream!.hasBytesAvailable {
let bytesRead: Int = inputStream!.read(&buffer, maxLength: buffer.count)
if bytesRead >= 0 {
guard let read = String(bytes: buffer[..<bytesRead], encoding: .utf8) else {
fatalError("Unable to decode bytes from buffer \(buffer[..<bytesRead])")
}
output.append(contentsOf: read)
} else {
verbose(message: "Stream read() error")
}
}
self.processResponse(string: output)
readSemaphore.signal()
}
}
func handleFailure(message: [String]) {
log(message: "Encountered a problem: \(message.joined(separator: "\n"))")
let shutdownCommand = ControlCommand(commandType: .cancel(cancelReason: .serverError))
send(rubyCommand: shutdownCommand)
}
func processResponse(string: String) {
guard !string.isEmpty else {
socketDelegate?.commandExecuted(serverResponse: .malformedResponse) {
self.handleFailure(message: ["empty response from ruby process"])
$0.writeSemaphore.signal()
}
return
}
let responseString = string.trimmingCharacters(in: .whitespacesAndNewlines)
let socketResponse = SocketResponse(payload: responseString)
verbose(message: "response is: \(responseString)")
switch socketResponse.responseType {
case .clientInitiatedCancel:
socketDelegate?.commandExecuted(serverResponse: .clientInitiatedCancelAcknowledged) {
$0.writeSemaphore.signal()
self.closeSession(sendAbort: false)
}
case let .failure(failureInformation, failureClass, failureMessage):
LaneFile.fastfileInstance?.onError(currentLane: ArgumentProcessor(args: CommandLine.arguments).currentLane, errorInfo: failureInformation.joined(), errorClass: failureClass, errorMessage: failureMessage)
socketDelegate?.commandExecuted(serverResponse: .serverError) {
$0.writeSemaphore.signal()
self.handleFailure(message: failureInformation)
}
case let .parseFailure(failureInformation):
socketDelegate?.commandExecuted(serverResponse: .malformedResponse) {
$0.writeSemaphore.signal()
self.handleFailure(message: failureInformation)
}
case let .readyForNext(returnedObject, closureArgumentValue):
socketDelegate?.commandExecuted(serverResponse: .success(returnedObject: returnedObject, closureArgumentValue: closureArgumentValue)) {
$0.writeSemaphore.signal()
}
}
}
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.2]
| d66706662c5861375d876d1694b85885 | 35.289157 | 215 | 0.639525 | false | false | false | false |
panjinqiang11/Swift-WeiBo | refs/heads/master | WeiBo/WeiBo/Class/ModelView/PJUserAccountViewModel.swift | mit | 1 | //
// PJUserAccountViewModel.swift
// WeiBo
//
// Created by 潘金强 on 16/7/12.
// Copyright © 2016年 潘金强. All rights reserved.
//
import UIKit
class PJUserAccountViewModel: NSObject {
//创建单例
static let shareUserAccount :PJUserAccountViewModel = PJUserAccountViewModel()
var userAccount:PJUserAount? {
return PJUserAount.loadUserAccount()
}
//私有化
private override init(){
super.init()
}
//判断accessToken是否为nil
var isLogin :Bool{
return accessToken != nil
}
var accessToken: String? {
guard let token = userAccount?.access_token else{
return nil
}
let result = userAccount?.expiresDate?.compare(NSDate())
if result == NSComparisonResult.OrderedDescending {
return token
}else{
return nil
}
}
//通过授权码获得accesstoken
func requestAccesstoken(code: String ,callBack: (isSuccess :Bool) -> ()) {
//调用PJNetworkTools中的requestAccessToken方法
PJNetworkTools.shareTools.requestAccessToken(code) { (response, error) -> () in
if error != nil{
callBack(isSuccess: false)
return//请求失败
}else {
//回调数据
guard let dic = response as? [String :AnyObject] else{
print("不是正确json格式")
return
}
//通过令牌获得用户信息
let user = PJUserAount(dic: dic)
self.requestUserInfo(user,callBack: callBack)
}
}
}
// MARK: - 请求用户信息
private func requestUserInfo(userAccount: PJUserAount,callBack: (isSuccess :Bool) -> ()){
PJNetworkTools.shareTools.requestUserInfo(userAccount) { (response, error) -> () in
if error != nil {
callBack(isSuccess: false)
return
}
guard let dic = response as? [String :AnyObject] else{
callBack(isSuccess: false)
return
}
let name = dic["name"]
let avatar_large = dic["avatar_large"]
// 设置用户名和头像
userAccount.name = name as? String
userAccount.avatar_large = avatar_large as? String
print(avatar_large)
// 保存用户对象
let result = userAccount.saveUserAccount()
if result {
callBack(isSuccess: true)
}else {
callBack(isSuccess: false)
}
}
}
}
| 5688eed4bdc1dccf4ab79bf8c42f186d | 22.464 | 93 | 0.463007 | false | false | false | false |
jakubknejzlik/ChipmunkSwiftWrapper | refs/heads/master | Pod/Classes/ChipmunkShape.swift | mit | 1 | //
// ChipmunkShape.swift
// Pods
//
// Created by Jakub Knejzlik on 15/11/15.
//
//
import Foundation
public class ChipmunkShape: ChipmunkSpaceObject {
weak var body: ChipmunkBody?
let shape: UnsafeMutablePointer<cpShape>
override var space: ChipmunkSpace? {
willSet {
if let space = self.space {
cpSpaceRemoveShape(space.space, self.shape)
}
}
didSet {
if let space = self.space {
if let body = self.body where body.isStatic {
cpSpaceAddStaticShape(space.space, self.shape)
} else {
cpSpaceAddShape(space.space, self.shape)
}
}
}
}
/** A boolean value if this shape is a sensor or not. Sensors only call collision callbacks, and never generate real collisions.*/
public var sensor: Bool {
get {
return Bool(cpShapeGetSensor(shape))
}
set(value) {
cpShapeSetSensor(shape, value.cpBool())
}
}
/** Elasticity of the shape. A value of 0.0 gives no bounce, while a value of 1.0 will give a “perfect” bounce. However due to inaccuracies in the simulation using 1.0 or greater is not recommended however. The elasticity for a collision is found by multiplying the elasticity of the individual shapes together. */
public var elasticity: Double {
get {
return Double(cpShapeGetElasticity(shape))
}
set(value) {
cpShapeSetElasticity(shape, cpFloat(value))
}
}
/** Friction coefficient. Chipmunk uses the Coulomb friction model, a value of 0.0 is frictionless. The friction for a collision is found by multiplying the friction of the individual shapes together. */
public var friction: Double {
get {
return Double(cpShapeGetFriction(shape))
}
set(value) {
cpShapeSetFriction(shape, cpFloat(value))
}
}
/** The surface velocity of the object. Useful for creating conveyor belts or players that move around. This value is only used when calculating friction, not resolving the collision. */
public var surfaceVelocity: CGPoint {
get {
return cpShapeGetSurfaceVelocity(shape)
}
set(value) {
cpShapeSetSurfaceVelocity(shape, value)
}
}
/** You can assign types to Chipmunk collision shapes that trigger callbacks when objects of certain types touch.*/
public var collisionType: AnyObject {
get {
return UnsafeMutablePointer<AnyObject>(bitPattern: cpShapeGetCollisionType(shape)).memory
}
set(value) {
let pointer = unsafeAddressOf(value)
cpShapeSetCollisionType(shape, pointer.getUIntValue())
}
}
/** Shapes in the same non-zero group do not generate collisions. Useful when creating an object out of many shapes that you don’t want to self collide. Defaults to CP_NO_GROUP. */
public var group: AnyObject {
get {
return UnsafeMutablePointer<AnyObject>(bitPattern: cpShapeGetGroup(shape)).memory
}
set(value) {
let pointer = unsafeAddressOf(value)
cpShapeSetGroup(shape, pointer.getUIntValue())
}
}
/** Shapes only collide if they are in the same bit-planes. i.e. (a->layers & b->layers) != 0 By default, a shape occupies all bit-planes. */
public var layers: UInt {
get {
return UInt(cpShapeGetLayers(shape))
}
set(value) {
cpShapeSetLayers(shape, UInt32(value))
}
}
init(body: ChipmunkBody, shape: UnsafeMutablePointer<cpShape>) {
self.body = body
self.shape = shape
super.init()
cpShapeSetUserData(shape, UnsafeMutablePointer<ChipmunkShape>(unsafeAddressOf(self)))
body.addShape(self)
}
public convenience init(body: ChipmunkBody, radius: Double, offset: CGPoint) {
self.init(body: body, shape: cpCircleShapeNew(body.body, cpFloat(radius), offset))
}
public convenience init(body: ChipmunkBody, size: CGSize) {
self.init(body: body, shape: cpBoxShapeNew(body.body, cpFloat(size.width), cpFloat(size.height)))
}
} | 52e47ac3e6a55e3d09cffd1fb77c4d35 | 35.141667 | 318 | 0.620849 | false | false | false | false |
wordpress-mobile/WordPress-iOS | refs/heads/trunk | WordPress/Classes/ViewRelated/Site Creation/Design Selection/Preview/TemplatePreviewViewController.swift | gpl-2.0 | 1 |
import Foundation
protocol TemplatePreviewViewDelegate {
typealias PreviewDevice = PreviewDeviceSelectionViewController.PreviewDevice
func deviceButtonTapped(_ previewDevice: PreviewDevice)
func deviceModeChanged(_ previewDevice: PreviewDevice)
func previewError(_ error: Error)
func previewViewed()
func previewLoading()
func previewLoaded()
func templatePicked()
}
class TemplatePreviewViewController: UIViewController, NoResultsViewHost, UIPopoverPresentationControllerDelegate {
typealias PreviewDevice = PreviewDeviceSelectionViewController.PreviewDevice
@IBOutlet weak var primaryActionButton: UIButton!
@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var footerView: UIView!
@IBOutlet weak var progressBar: UIProgressView!
internal var delegate: TemplatePreviewViewDelegate?
private let demoURL: String
private var estimatedProgressObserver: NSKeyValueObservation?
internal var selectedPreviewDevice: PreviewDevice {
didSet {
if selectedPreviewDevice != oldValue {
UIView.animate(withDuration: 0.2, animations: {
self.webView.alpha = 0
}, completion: { _ in
self.progressBar.animatableSetIsHidden(false)
self.webView.reload()
})
}
}
}
private var onDismissWithDeviceSelected: ((PreviewDevice) -> ())?
lazy var ghostView: GutenGhostView = {
let ghost = GutenGhostView()
ghost.hidesToolbar = true
ghost.translatesAutoresizingMaskIntoConstraints = false
return ghost
}()
private var accentColor: UIColor {
return UIColor { (traitCollection: UITraitCollection) -> UIColor in
if traitCollection.userInterfaceStyle == .dark {
return UIColor.muriel(color: .primary, .shade40)
} else {
return UIColor.muriel(color: .primary, .shade50)
}
}
}
init(demoURL: String, selectedPreviewDevice: PreviewDevice?, onDismissWithDeviceSelected: ((PreviewDevice) -> ())?) {
self.demoURL = demoURL
self.selectedPreviewDevice = selectedPreviewDevice ?? PreviewDevice.default
self.onDismissWithDeviceSelected = onDismissWithDeviceSelected
super.init(nibName: "\(TemplatePreviewViewController.self)", bundle: .main)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
removeProgressObserver()
}
override func viewDidLoad() {
super.viewDidLoad()
configureWebView()
styleButtons()
webView.scrollView.contentInset.bottom = footerView.frame.height
webView.navigationDelegate = self
webView.backgroundColor = .basicBackground
delegate?.previewViewed()
observeProgressEstimations()
configurePreviewDeviceButton()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
onDismissWithDeviceSelected?(selectedPreviewDevice)
}
@IBAction func actionButtonSelected(_ sender: Any) {
dismiss(animated: true)
delegate?.templatePicked()
}
private func configureWebView() {
webView.alpha = 0
guard let demoURL = URL(string: demoURL) else { return }
let request = URLRequest(url: demoURL)
webView.customUserAgent = WPUserAgent.wordPress()
webView.load(request)
}
private func styleButtons() {
primaryActionButton.titleLabel?.font = WPStyleGuide.fontForTextStyle(.body, fontWeight: .medium)
primaryActionButton.backgroundColor = accentColor
primaryActionButton.layer.cornerRadius = 8
primaryActionButton.setTitle(NSLocalizedString("Choose", comment: "Title for the button to progress with the selected site homepage design"), for: .normal)
}
private func configurePreviewDeviceButton() {
let button = UIBarButtonItem(image: UIImage(named: "icon-devices"), style: .plain, target: self, action: #selector(previewDeviceButtonTapped))
navigationItem.rightBarButtonItem = button
}
private func observeProgressEstimations() {
estimatedProgressObserver = webView.observe(\.estimatedProgress, options: [.new]) { [weak self] (webView, _) in
self?.progressBar.progress = Float(webView.estimatedProgress)
}
}
@objc func closeButtonTapped() {
dismiss(animated: true)
}
@objc private func previewDeviceButtonTapped() {
delegate?.deviceButtonTapped(selectedPreviewDevice)
let popoverContentController = PreviewDeviceSelectionViewController()
popoverContentController.selectedOption = selectedPreviewDevice
popoverContentController.onDeviceChange = { [weak self] device in
guard let self = self else { return }
self.delegate?.deviceModeChanged(device)
self.selectedPreviewDevice = device
}
popoverContentController.modalPresentationStyle = .popover
popoverContentController.popoverPresentationController?.delegate = self
self.present(popoverContentController, animated: true, completion: nil)
}
private func removeProgressObserver() {
estimatedProgressObserver?.invalidate()
estimatedProgressObserver = nil
}
private func handleError(_ error: Error) {
delegate?.previewError(error)
configureAndDisplayNoResults(on: webView,
title: NSLocalizedString("Unable to load this content right now.", comment: "Informing the user that a network request failed because the device wasn't able to establish a network connection."))
progressBar.animatableSetIsHidden(true)
}
}
// MARK: WKNavigationDelegate
extension TemplatePreviewViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
delegate?.previewLoading()
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
handleError(error)
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
webView.evaluateJavaScript(selectedPreviewDevice.viewportScript)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
handleError(error)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
UIView.animate(withDuration: 0.2) {
self.webView.alpha = 1
}
delegate?.previewLoaded()
progressBar.animatableSetIsHidden(true)
}
}
// MARK: UIPopoverPresentationDelegate
extension TemplatePreviewViewController {
func prepareForPopoverPresentation(_ popoverPresentationController: UIPopoverPresentationController) {
guard popoverPresentationController.presentedViewController is PreviewDeviceSelectionViewController else {
return
}
popoverPresentationController.permittedArrowDirections = .up
popoverPresentationController.barButtonItem = navigationItem.rightBarButtonItem
}
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
guard let popoverPresentationController = presentedViewController?.presentationController as? UIPopoverPresentationController else {
return
}
prepareForPopoverPresentation(popoverPresentationController)
}
}
| 9f8abc01404b467eea1d84debd5a6fd3 | 37.126214 | 231 | 0.700535 | false | false | false | false |
OneBusAway/onebusaway-iphone | refs/heads/develop | Carthage/Checkouts/SwiftEntryKit/Source/MessageViews/EKRatingMessageView.swift | apache-2.0 | 3 | //
// EKRatingMessageView.swift
// SwiftEntryKit
//
// Created by Daniel Huri on 6/1/18.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
import QuickLayout
public class EKRatingMessageView: UIView, EntryAppearanceDescriptor {
// MARK: Properties
private var message: EKRatingMessage
// MARK: EntryAppearenceDescriptor
var bottomCornerRadius: CGFloat = 0 {
didSet {
buttonBarView.bottomCornerRadius = bottomCornerRadius
}
}
private var selectedIndex: Int! {
didSet {
message.selectedIndex = selectedIndex
let item = message.ratingItems[selectedIndex]
set(title: item.title, description: item.description)
}
}
private let messageContentView = EKMessageContentView()
private let symbolsView = EKRatingSymbolsContainerView()
private var buttonBarView: EKButtonBarView!
public init(with message: EKRatingMessage) {
self.message = message
super.init(frame: UIScreen.main.bounds)
setupMessageContentView()
setupSymbolsView()
setupButtonBarView()
set(title: message.initialTitle, description: message.initialDescription)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func set(title: EKProperty.LabelContent, description: EKProperty.LabelContent) {
self.messageContentView.titleContent = title
self.messageContentView.subtitleContent = description
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [.transitionCrossDissolve], animations: {
SwiftEntryKit.layoutIfNeeded()
}, completion: nil)
}
private func setupMessageContentView() {
addSubview(messageContentView)
messageContentView.verticalMargins = 20
messageContentView.horizontalMargins = 30
messageContentView.layoutToSuperview(axis: .horizontally, priority: .must)
messageContentView.layoutToSuperview(.top, offset: 10)
}
private func setupSymbolsView() {
addSubview(symbolsView)
symbolsView.setup(with: message) { [unowned self] (index: Int) in
self.message.selectedIndex = index
self.message.selection?(index)
self.selectedIndex = index
self.animateIn()
}
symbolsView.layoutToSuperview(.centerX)
symbolsView.layout(.top, to: .bottom, of: messageContentView, offset: 10, priority: .must)
}
private func setupButtonBarView() {
buttonBarView = EKButtonBarView(with: message.buttonBarContent)
buttonBarView.clipsToBounds = true
buttonBarView.alpha = 0
addSubview(buttonBarView)
buttonBarView.layout(.top, to: .bottom, of: symbolsView, offset: 30)
buttonBarView.layoutToSuperview(.bottom)
buttonBarView.layoutToSuperview(axis: .horizontally)
}
// MARK: Internal Animation
private func animateIn() {
layoutIfNeeded()
buttonBarView.expand()
}
}
| 80474934b02118f928a687482a596bfd | 32.744681 | 155 | 0.672762 | false | false | false | false |
seandavidmcgee/HumanKontactBeta | refs/heads/master | src/HumanKontact Extension/ProfileController2.swift | mit | 1 | //
// ProfileController2.swift
// keyboardTest
//
// Created by Sean McGee on 7/21/15.
// Copyright (c) 2015 3 Callistos Services. All rights reserved.
//
import WatchKit
import Foundation
import RealmSwift
class ProfileController2: WKInterfaceController {
@IBOutlet weak var profileBG: WKInterfaceGroup!
@IBOutlet weak var contactType: WKInterfaceLabel!
@IBOutlet weak var contactAvatar: WKInterfaceImage!
@IBOutlet weak var contactFirstName: WKInterfaceLabel!
@IBOutlet weak var contactLastName: WKInterfaceLabel!
@IBOutlet weak var contactInitials: WKInterfaceLabel!
@IBOutlet weak var contactInitialsGroup: WKInterfaceGroup!
@IBOutlet weak var contactInitialsAvatar: WKInterfaceGroup!
@IBOutlet weak var contactPhone: WKInterfaceLabel!
@IBOutlet weak var contactCall: WKInterfaceGroup!
@IBOutlet weak var contactText: WKInterfaceGroup!
@IBOutlet weak var contactAvatarGroup: WKInterfaceGroup!
var firstName: String!
var lastName: String!
var avatar: NSData!
var initials: String!
var color: UIColor!
var phones: List<HKPhoneNumber>!
var phoneString: String!
var profilePhoneString: String!
var profilePhoneLabelString: String!
var person: String!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
firstName = (context as! NSDictionary)["firstName"] as? String
lastName = (context as! NSDictionary)["lastName"] as? String
avatar = (context as! NSDictionary)["avatar"] as? NSData
initials = (context as! NSDictionary)["initials"] as? String
color = (context as! NSDictionary)["color"] as? UIColor
phones = ((context as! NSDictionary)["phone"] as? List<HKPhoneNumber>)!
person = (context as! NSDictionary)["person"] as? String
contactName()
avatarView()
profilePhones()
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
@IBAction func callPhone() {
forwardCall(profilePhoneString)
//presentControllerWithName("Handoff", context: nil)
}
@IBAction func textPhone() {
forwardText(profilePhoneString)
//presentControllerWithName("Handoff", context: nil)
}
@IBAction func goToPersonOnPhone() {
forwardPerson(person)
presentControllerWithName("Handoff", context: nil)
}
func contactName() {
if firstName != nil && lastName != nil {
self.contactFirstName.setText(firstName)
self.contactLastName.setText(lastName)
self.contactFirstName.setTextColor(color)
self.contactLastName.setTextColor(color)
} else if firstName != nil && lastName == nil {
self.contactFirstName.setText(firstName)
self.contactFirstName.setTextColor(color)
} else {
self.contactLastName.setText(lastName)
self.contactLastName.setTextColor(color)
}
}
func avatarView() {
if avatar != nil {
self.contactAvatarGroup.setBackgroundColor(color)
self.contactAvatar.setImageData(avatar)
self.contactAvatar.setHidden(false)
self.contactInitialsGroup.setHidden(true)
} else {
self.contactAvatarGroup.setHidden(true)
self.contactInitialsAvatar.setHidden(false)
self.contactInitialsAvatar.setBackgroundColor(color)
self.contactInitials.setText(initials)
}
}
func forwardCall(forwardText: String) {
let contactNumber = callNumber(forwardText)
let phoneCallURL = NSURL(string: "tel://\(contactNumber)")!
WKExtension.sharedExtension().openSystemURL(phoneCallURL)
}
func forwardText(forwardText: String) {
let contactNumber = callNumber(forwardText)
let phoneCallURL = NSURL(string: "sms://\(contactNumber)")!
WKExtension.sharedExtension().openSystemURL(phoneCallURL)
}
func forwardPerson(forwardPerson: String) {
let personProfile = forwardPerson
updateUserActivity(ActivityKeys.ChoosePerson, userInfo: ["person": personProfile], webpageURL: nil)
}
func callNumber(sender: String) -> String {
let phoneNumber = sender
let strippedPhoneNumber = phoneNumber.stringByReplacingOccurrencesOfString("[^0-9 ]", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range:nil);
var cleanNumber = strippedPhoneNumber.removeWhitespace()
cleanNumber = cleanNumber.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return cleanNumber
}
func profilePhones() {
if let hkPhone = phones[1] as HKPhoneNumber! {
profilePhoneString = phoneString
profilePhoneLabelString = hkPhone.label
switch profilePhoneLabelString {
case "Mobile":
contactCall.setBackgroundImageNamed("WatchMobile")
contactText.setBackgroundImageNamed("WatchMessage")
case "Work":
contactCall.setBackgroundImageNamed("WatchWork")
case "Home":
contactCall.setBackgroundImageNamed("WatchHome")
case "Main":
contactCall.setBackgroundImageNamed("WatchHome")
case "iPhone":
contactCall.setBackgroundImageNamed("WatchiPhone")
contactText.setBackgroundImageNamed("WatchMessageiPhone")
default:
contactCall.setBackgroundImageNamed("WatchHome")
}
self.contactType.setText(profilePhoneLabelString)
self.contactPhone.setText(profilePhoneString)
} else {
self.contactPhone.setText("")
}
}
func profilePhone(number: String) -> String {
var phoneNumber: String!
if let labelIndex = number.characters.indexOf(":") {
phoneNumber = number.substringFromIndex(labelIndex.successor())
}
return phoneNumber
}
func profilePhoneLabel(number: String) -> String {
var phoneLabel: String!
if let labelIndex = number.characters.indexOf(":") {
let label: String = number.substringToIndex(labelIndex)
phoneLabel = label
} else {
phoneLabel = "Phone"
}
return phoneLabel
}
}
| b6beca82d27c8b5532a80b1ed478596b | 36.59887 | 178 | 0.653644 | false | false | false | false |
DianQK/RxExample | refs/heads/master | RxZhihuDaily/Extension/UINavgationExtension.swift | mit | 1 | //
// UINavgationExtension.swift
// RxExample
//
// Created by 宋宋 on 16/2/15.
// Copyright © 2016年 DianQK. All rights reserved.
//
import UIKit
private var key: Void?
///https://github.com/ltebean/LTNavigationBar/blob/master/LTNavigationBar/UINavigationBar%2BAwesome.m
extension UINavigationBar {
var overlay: UIView? {
get {
return objc_getAssociatedObject(self, &key) as? UIView
}
set {
objc_setAssociatedObject(self, &key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var lt_backgroundColor: UIColor? {
get {
if self.overlay == nil {
self.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.overlay = UIView(frame: CGRect(x: 0, y: -20, width: UIScreen.mainScreen().bounds.size.width, height: CGRectGetHeight(self.bounds) + 20))
self.overlay?.userInteractionEnabled = false
self.overlay?.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.insertSubview(self.overlay!, atIndex: 0)
}
return self.overlay?.backgroundColor
}
set {
if self.overlay == nil {
self.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.overlay = UIView(frame: CGRect(x: 0, y: -20, width: UIScreen.mainScreen().bounds.size.width, height: CGRectGetHeight(self.bounds) + 20))
self.overlay?.userInteractionEnabled = false
self.overlay?.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.insertSubview(self.overlay!, atIndex: 0)
}
self.overlay?.backgroundColor = newValue
}
}
}
| db7d2244f092a291a4fc27c22f17e742 | 37.533333 | 157 | 0.607843 | false | false | false | false |
micchyboy1023/Today | refs/heads/dev | Today iOS App/Today Extension/TodayExtensionViewController.swift | mit | 1 | //
// TodayViewController.swift
// TodayExtension
//
// Created by UetaMasamichi on 2016/01/20.
// Copyright © 2016年 Masamichi Ueta. All rights reserved.
//
import UIKit
import TodayKit
import NotificationCenter
final class TodayExtensionViewController: UIViewController, NCWidgetProviding {
@IBOutlet weak var tableView: UITableView!
fileprivate let tableViewRowHeight: CGFloat = 44.0
fileprivate let rowNum = 4
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
self.extensionContext?.widgetLargestAvailableDisplayMode = .expanded
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func widgetPerformUpdate(completionHandler: @escaping (NCUpdateResult) -> Void) {
completionHandler(NCUpdateResult.newData)
}
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
if activeDisplayMode == .compact {
self.preferredContentSize = maxSize
} else {
self.preferredContentSize = CGSize(width: tableView.frame.width, height: tableViewRowHeight * 4)
}
}
private func setupTableView() {
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = tableViewRowHeight
}
}
extension TodayExtensionViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rowNum
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let sharedData = AppGroupSharedData.shared
switch (indexPath as NSIndexPath).row {
case 0:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "TodayExtensionCell", for: indexPath) as? TodayExtensionTodayTableViewCell else {
fatalError("Wrong cell type")
}
cell.configureForObject(sharedData.todayScore)
//For tap bug
cell.backgroundView = UILabel()
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "TodayExtensionKeyValueExtensionCell", for: indexPath)
cell.textLabel?.text = localize("Total")
cell.detailTextLabel?.text = "\(sharedData.total) " + localize("days")
//For tap bug
cell.backgroundView = UILabel()
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "TodayExtensionKeyValueExtensionCell", for: indexPath)
cell.textLabel?.text = localize("Longest streak")
cell.detailTextLabel?.text = "\(sharedData.longestStreak) " + localize("days")
//For tap bug
cell.backgroundView = UILabel()
return cell
case 3:
let cell = tableView.dequeueReusableCell(withIdentifier: "TodayExtensionKeyValueExtensionCell", for: indexPath)
cell.textLabel?.text = localize("Current streak")
cell.detailTextLabel?.text = "\(sharedData.currentStreak) " + localize("days")
//For tap bug
cell.backgroundView = UILabel()
return cell
default:
fatalError("Wront cell number")
}
//dummy
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let url = URL(string: appGroupURLScheme + "://") else {
return
}
extensionContext?.open(url,
completionHandler: nil)
}
}
| 610836811ce45548ee5e5fbd5c0ed018 | 34.261261 | 156 | 0.644354 | false | false | false | false |
wangchong321/tucao | refs/heads/master | WCWeiBo/WCWeiBo/Classes/Module/User.swift | mit | 1 | //
// User.swift
// WCWeiBo
//
// Created by 王充 on 15/5/18.
// Copyright (c) 2015年 wangchong. All rights reserved.
//
import UIKit
class User: NSObject {
/// 用户UID
var id : Int = 0
/// 友好显示名称
var name : String?
/// 用户头像地址(中图),50×50像素
var profile_image_url :String? {
didSet{
iconUrl = NSURL(string: profile_image_url!)
}
}
// 头像url
var iconUrl : NSURL?
/// 是否是微博认证用户,即加V用户,true:是,false:否
var verified: Bool = false
/// 认证类型 -1:没有认证,0,认证用户,2,3,5: 企业认证,220: 草根明星
var verified_type : Int = -1
/// 属性数组
// 1~6 一共6级会员
var mbrank: Int = 0
private static let proparties = ["id","name","profile_image_url","verified","verified_type","mbrank"]
init(dic : [String : AnyObject]){
super.init()
for key in User.proparties {
if dic[key] != nil {
setValue(dic[key], forKey: key)
}
}
}
}
| 107a1ed8948292a6b583915e3e4ed72f | 21.181818 | 105 | 0.522541 | false | false | false | false |
avhurst/week3 | refs/heads/master | InstaClone/InstaClone/Filters.swift | mit | 1 | //
// Filters.swift
// InstaClone
//
// Created by Allen Hurst on 2/16/16.
// Copyright © 2016 Allen Hurst. All rights reserved.
//
import UIKit
typealias FiltersCompletion = (theImage: UIImage?) -> ()
class Filters
{
static let shared = Filters()
var gpuContext: CIContext
private init() {
let options = [kCIContextWorkingColorSpace: NSNull()]
let EAGContext = EAGLContext(API: .OpenGLES2)
gpuContext = CIContext(EAGLContext: EAGContext, options: options)
}
private func filter(name: String, image: UIImage, completion: FiltersCompletion)
{
NSOperationQueue().addOperationWithBlock{ () -> Void in
guard let filter = CIFilter(name: name) else { fatalError("Check filter spelling") }
filter.setValue(CIImage(image: image), forKey: kCIInputImageKey)
//GPU Context
//get the final image
guard let outputImage = filter.outputImage else { fatalError("Why no image?") }
let CGImage = self.gpuContext.createCGImage(outputImage, fromRect: outputImage.extent)
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
completion(theImage: UIImage(CGImage: CGImage))
})
}
}
func bw(image: UIImage, completion: FiltersCompletion)
{
self.filter("CIPhotoEffectMono", image: image, completion: completion)
}
func px(image: UIImage, completion: FiltersCompletion)
{
self.filter("CIPixellate", image: image, completion: completion)
}
func invert(image: UIImage, completion: FiltersCompletion)
{
self.filter("CIColorInvert", image: image, completion: completion)
}
func sepia(image: UIImage, completion: FiltersCompletion)
{
self.filter("CISepiaTone", image: image, completion: completion)
}
func line(image: UIImage, completion: FiltersCompletion)
{
self.filter("CILineScreen", image: image, completion: completion)
}
} | 2705cd012e2551948478b070e038a444 | 26.329114 | 98 | 0.608434 | false | false | false | false |
skedgo/tripkit-ios | refs/heads/main | Sources/TripKitUI/cards/TKUINearbyMapManager.swift | apache-2.0 | 1 | //
// TKUINearbyMapManager.swift
// TripKitUI
//
// Created by Adrian Schoenig on 19/5/17.
// Copyright © 2017 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import MapKit
import RxSwift
import RxCocoa
import TripKit
public class TKUINearbyMapManager: TKUIMapManager {
public weak var viewModel: TKUINearbyViewModel?
public override init() {
super.init()
self.preferredZoomLevel = .road
self.showOverlayPolygon = true
}
private var mapTrackingPublisher = PublishSubject<MKUserTrackingMode>()
private var mapRectPublisher = PublishSubject<MKMapRect>()
public var mapCenter: Driver<CLLocationCoordinate2D?> {
mapRect.map { MKMapRectEqualToRect($0, .null) ? nil : MKCoordinateRegion($0).center }
}
public var mapRect: Driver<MKMapRect> {
mapRectPublisher.asDriver(onErrorJustReturn: .null)
}
private var tapRecognizer = UITapGestureRecognizer()
private var mapSelectionPublisher = PublishSubject<TKUIIdentifiableAnnotation?>()
public var mapSelection: Signal<TKUIIdentifiableAnnotation?> {
return mapSelectionPublisher.asSignal(onErrorJustReturn: nil)
}
public var searchResult: MKAnnotation? {
didSet {
updateSearchResult(searchResult, previous: oldValue)
}
}
private var disposeBag = DisposeBag()
override public func takeCharge(of mapView: MKMapView, animated: Bool) {
super.takeCharge(of: mapView, animated: animated)
if viewModel == nil {
viewModel = TKUINearbyViewModel.homeInstance
}
guard let viewModel = viewModel else { assertionFailure(); return }
// Default content on taking charge
mapView.showsScale = true
let showCurrentLocation = TKLocationManager.shared.authorizationStatus == .authorized
mapView.showsUserLocation = showCurrentLocation
if let searchResult = self.searchResult {
mapView.setUserTrackingMode(.none, animated: animated)
mapView.addAnnotation(searchResult)
zoom(to: [searchResult], animated: animated)
} else if let start = viewModel.fixedLocation {
mapView.setUserTrackingMode(.none, animated: animated)
zoom(to: [start], animated: animated)
} else if showCurrentLocation {
mapView.setUserTrackingMode(.follow, animated: animated)
}
// Dynamic content
viewModel.mapAnnotations
.drive(onNext: { [weak self] annotations in
guard let self = self else { return }
self.animatedAnnotations = annotations
})
.disposed(by: disposeBag)
viewModel.mapAnnotationToSelect
.emit(onNext: { [weak self] annotation in
guard let mapView = self?.mapView else { return }
guard let onMap = mapView.annotations.first(where: { ($0 as? TKUIIdentifiableAnnotation)?.identity == annotation.identity }) else {
assertionFailure("We were asked to select annotation with identity \(annotation.identity ?? "nil"), but that hasn't been added to the map. Available: \(mapView.annotations.compactMap { ($0 as? TKUIIdentifiableAnnotation)?.identity }.joined(separator: ", "))")
return
}
let alreadySelected = mapView.selectedAnnotations.contains(where: {
$0.coordinate.latitude == onMap.coordinate.latitude &&
$0.coordinate.longitude == onMap.coordinate.longitude
})
if alreadySelected {
// We deselect the annotation, so mapView(_:didSelect:) can fire if the same
// one is selected. This closes https://redmine.buzzhives.com/issues/10190.
mapView.deselectAnnotation(onMap, animated: false)
// We chose not to animate so the annotation appear fixed in place when we
// deselect and then select.
mapView.selectAnnotation(onMap, animated: false)
} else {
mapView.selectAnnotation(onMap, animated: true)
}
})
.disposed(by: disposeBag)
viewModel.mapOverlays
.drive(onNext: { [weak self] overlays in
guard let self = self else { return }
self.overlays = overlays
})
.disposed(by: disposeBag)
viewModel.searchResultToShow
.drive(rx.searchResult)
.disposed(by: disposeBag)
// Action on MKOverlay
mapView.addGestureRecognizer(tapRecognizer)
tapRecognizer.rx.event
.filter { $0.state == .ended }
.compactMap { [weak self] in self?.closestAnnotation(to: $0) }
.bind(to: mapSelectionPublisher)
.disposed(by: disposeBag)
}
override public func cleanUp(_ mapView: MKMapView, animated: Bool) {
disposeBag = DisposeBag()
if let searchResult = self.searchResult {
mapView.removeAnnotation(searchResult)
}
super.cleanUp(mapView, animated: animated)
}
private func closestLine(to coordinate: CLLocationCoordinate2D) -> TKRoutePolyline? {
guard let mapView = self.mapView else { return nil }
let routes = mapView.overlays.compactMap { $0 as? TKRoutePolyline }
let mapPoint = MKMapPoint(coordinate)
return routes.filter { $0.distance(to: mapPoint) < 44 }.min { $0.distance(to: mapPoint) < $1.distance(to: mapPoint) }
}
private func closestAnnotation(to tap: UITapGestureRecognizer) -> TKUIIdentifiableAnnotation? {
guard let mapView = self.mapView else { assertionFailure(); return nil }
let point = tap.location(in: mapView)
let coordinate = mapView.convert(point, toCoordinateFrom: mapView)
guard let line = closestLine(to: coordinate) else { return nil }
return line.route as? TKUIIdentifiableAnnotation
}
}
extension TKRoutePolyline {
fileprivate func distance(to mapPoint: MKMapPoint) -> CLLocationDistance {
return closestPoint(to: mapPoint).distance
}
}
extension TKUINearbyMapManager {
public func mapView(_ mapView: MKMapView, didChange mode: MKUserTrackingMode, animated: Bool) {
mapTrackingPublisher.onNext(mode)
}
public override func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
super.mapView(mapView, regionDidChangeAnimated: animated)
mapRectPublisher.onNext(mapView.visibleMapRect)
}
public override func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
super.mapView(mapView, didSelect: view)
guard let identifiable = view.annotation as? TKUIIdentifiableAnnotation else { return }
mapSelectionPublisher.onNext(identifiable)
}
}
// MARK: Search result
extension Reactive where Base: TKUINearbyMapManager {
@MainActor
var searchResult: Binder<MKAnnotation?> {
return Binder(self.base) { mapManager, annotation in
mapManager.searchResult = annotation
}
}
}
extension TKUINearbyMapManager {
func updateSearchResult(_ annotation: MKAnnotation?, previous: MKAnnotation?) {
guard let mapView = mapView else { return }
if let old = previous {
mapView.removeAnnotation(old)
}
if let new = annotation {
mapView.addAnnotation(new)
zoom(to: [new], animated: true)
}
}
}
| f44db6d0cd1a3df1d0d79ea25fd9b80b | 31.228311 | 269 | 0.692689 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.